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

By Hardik Savani November 5, 2023 Category : 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 App\Http\Controllers;

use Illuminate\Http\Request;

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 App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Controllers\OtherController;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

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

dd($result);

}

}

Output:

From Another Controller Text

Example 2:

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$result = app('App\Http\Controllers\OtherController')->exampleFunction();

dd($result);

}

}

Output:

From Another Controller Text

Example 3:

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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...

Tags :
Shares