In this article we will learn Call Controller Method from Another Controller in Laravel. Sometimes we need to access the controller method from another controller to save the same code on multiple locations. Best way to achieve it is using create a separate service class or trait in PHP so that we can import the class in both controllers but in case due to lack of time or any reason we can’t able to create these class than larvae also offers to call controller function or method from another controller.
Method 1 : Call Controller Method from Another Controller in Laravel
Suppose you have a controller class name
and another class TestAController
TestBController
, Class
contains a method TestAController
print()
and you want to access the print method in class b so
<?php
class TestAController extends Controller{
function print(){
return "print";
}
}
class TestBController extends Controller{
function testB(){
app('App\Http\Controllers\TestAControler')->print();
}
}
Here we used laravel app function to create the object of TestAController
class and then called the print method.
it’s generally not recommended to directly call a method from one controller in another controller. Controllers in Laravel are designed to handle HTTP requests and responses, and they should remain independent of each other.
Method 2 : Inherit the class by extending the parent class
In this method we will inherit class TestAController
to class TestBController
as below
<?php
class TestAController extends Controller{
function print(){
return "print";
}
}
class TestBController extends TestAController{
function testB(){
return $this->print();
}
}
Method 3 : Using the trait to share the same methods in controllers
Directly calling one controller method from another controller in Laravel is generally not recommended, as controllers should be kept thin and focused on handling HTTP requests and responses. However, if you have a specific use case that requires this, you can achieve it by using traits or by extending a base controller class.
So create a trait in folder app-> traits if you do not have folder then create the folder first.
<?php
namespace App\Traits;
trait CommonMethods{
function print(){
return "print";
}
}
now us it in both controlllers as below
<?php
class TestAController extends Controller{
use App\Traits\CommonMethods;
function method1(){
return $this->print();
}
}
class TestBController extends TestAController{
use App\Traits\CommonMethods;
function method2(){
return $this->print();
}
}
Method 4 : Create object of Controller
in this method we will create the object of first controller and then will use it in B controller
<?php
class TestAController extends Controller{
function print(){
return "print";
}
}
class TestBController extends Controller{
function testB(){
$aContoller = new \App\Http\Controllers\TestAControler;
$aContoller->print();
}
}