Hello Friends,

Welcome To Infinitbility!

If you are stuck calling function from another controller, relax you will definitely get a solution from this article.

If you want to use controller function please follow the business logic structure of laravel. sometimes it’s the reason of memory leak and security issue. I will never recommend using this method on your project.

here I will share two controllers to easily understand the calling a function from another controller.

Child Controller


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ChildController extends Controller
{
    
    /**
     * Common function using on multiple controller
     */
    public function Calculation($firstNumber, $operator, $secondnumber){

        if($operator == '+'){
            $response = $firstNumber + $secondnumber;
        }elseif($operator == '-'){
            $response = $firstNumber - $secondnumber;
        }elseif($operator == '*'){
            $response = $firstNumber * $secondnumber;
        }elseif($operator == '/'){
            $response = $firstNumber / $secondnumber;
        }
        
        return $response;
    }

}

Parent Controller


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\ChildController;

class ParentController extends Controller
{
    protected $ChildController;
    public function __construct(ChildController $ChildController)
    {
        $this->ChildController = $ChildController;
    }

    /**
     * Parent function using child function
     */
    function calc(Request $Request){

        $firstNumber = $Request->input('firstNumber');
        $operator = $Request->input('operator'); 
        $secondnumber = $Request->input('secondnumber');

        $response = $this->ChildController->Calculation($firstNumber, $operator, $secondnumber);
        return $response;
    }
}   

Thanks for reading…

Yajra issue after install in laravel

Laravel call function from another class

laravel pagination with customization

How to solve page expired error in laravel for webhooks, ajax, and form

Laravel Model

Laravel Clear cache, config, view and Routes

how to force Laravel to use https in URL and assets