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
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use Illuminate\Http\Request;78class ChildController extends Controller9{1011 /**12 * Common function using on multiple controller13 */14 public function Calculation($firstNumber, $operator, $secondnumber){1516 if($operator == '+'){17 $response = $firstNumber + $secondnumber;18 }elseif($operator == '-'){19 $response = $firstNumber - $secondnumber;20 }elseif($operator == '*'){21 $response = $firstNumber * $secondnumber;22 }elseif($operator == '/'){23 $response = $firstNumber / $secondnumber;24 }2526 return $response;27 }2829}
Parent Controller
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use Illuminate\Http\Request;7use App\Http\Controllers\ChildController;89class ParentController extends Controller10{11 protected $ChildController;12 public function __construct(ChildController $ChildController)13 {14 $this->ChildController = $ChildController;15 }1617 /**18 * Parent function using child function19 */20 function calc(Request $Request){2122 $firstNumber = $Request->input('firstNumber');23 $operator = $Request->input('operator');24 $secondnumber = $Request->input('secondnumber');2526 $response = $this->ChildController->Calculation($firstNumber, $operator, $secondnumber);27 return $response;28 }29}
if you get help, please share post on your social network