Categories
Learning

How to call Laravel one Controller method into another?

Hello welcome to this post!

As of part of learning and development of laravel project I was simply looking syntax how to call laravel controller method in another controller.

Here is some tips and example:

Make sure you declared function as with public keyword while defining any method/function in controller.

Method updateMethod defined in controller called DoctorController.php as follow:

public function updateMethod($request, $id) {
// echo $id;
. . . // more lines of your code here
}

Secondly calling updateMethod in controller called DoctorApiController.php

public function updateDoctor(Request $request, $id) {
      if (Doctor::where('id', $id)->exists()) {
        $result = (new DoctorController)->updateMethod($request, $id);
        
        return response()->json([
            "message" => "Doctor updated successfully"
        ], 200);
        } else {
        return response()->json([
            "message" => "Doctor not found"
        ], 404);
        
    }
   }

If you got any error with DoctorController or your Controller class name not found or any such please add: use App\Http\Controllers\DoctorController; on top of the file.

This was the one way to simply call method of laravel one controller to other.

Hope it helpful. Thanks for visiting and reading.