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.

admin

Recent Posts

The Ultimate Guide to Effective Meetings

In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…

2 months ago

From Mine to Market: How Gold Is Mined, Refined, and Sold in Shops

Gold is one of the most coveted precious metals in the world, adored for its…

3 months ago

The Historical Journey of Gold: From Ancient Civilizations to Modern Times

Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…

3 months ago

How to Onboard an Intern in Small, Individual-Based Company

How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…

4 months ago