Is it possible to call a method from one controller inside another controller in Laravel 5 (regardless the http method used to access each method)?
Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.
Controllers are apex classes so you just need to instantiate your second controller in the first, set whatever data you need to set and then call the method like any other class.
This is how I have done it. Use the use
keyword to make the OtherController available. Then you can call a method from that class on instantiation.
<?php namespace App\Http\Controllers;
use App\Http\Controllers\OtherController;
class MyController extends Controller {
public function __construct()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
Also check out the concept of a Command in Laravel. It might give you more flexibility than the method above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With