How to Call a Controller Function in Another Controller in Laravel?

Hey Developer,

Now, let’s see a tutorial of laravel call function from another controller. let’s discuss laravel call controller method from another controller. This tutorial will give you a simple example of use controller in another controller laravel. I want to show you how to call controller function in another controller in laravel.

Sometimes, we need to call the controller method in another controller, that’s the reason laravel provides, several ways to call the controller function in another controller. Without any further ado, let’s see below code example.

In this example, we will create “OtherController” with two method with public “exampleFunction()” and static “exampleFunctionStatic()” method. Then we will call those functions in “PostController”. so let’s see below three ways.

Create OtherController

let’s create one controller for our examples.

OtherController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class OtherController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function exampleFunction()

{

return "From Another Controller Text";

}

/**

* Write code on Method

*

* @return response()

*/

static function exampleFunctionStatic()

{

return "From Another Controller Text";

}

}

Example 1:

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpControllersOtherController;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$result = (new OtherController)->exampleFunction();

dd($result);

}

}

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:auto!important;margin-right:auto!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

Output:

From Another Controller Text

Example 2:

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$result = app('AppHttpControllersOtherController')->exampleFunction();

dd($result);

}

}

Output:

From Another Controller Text

Example 3:

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$result = OtherController::exampleFunctionStatic();

dd($result);

}

}

Output:

From Another Controller Text

I hope it can help you…

Leave a Comment