samedi 3 août 2019

Laravel contructor and method injection

Am having an issue setting up an injection on both the constructor and the method in a controller.

What I need to achive is to be able to setup a global controller variable without injecting teh same on the controller method.

From below route;

Route::group(['prefix' => 'test/{five}'], function(){
    Route::get('/index/{admin}', 'TestController@index');
});

I want the five to be recieved by the constructor while the admin to be available to the method. Below is my controller;

class TestController extends Controller
{
   private $five;
    public function __construct(PrimaryFive $five,Request $request)
    {
        $this->five=$five;
    }

    public function index(Admin $admin,Request $request)
    {
        dd($request->segments(),$admin);
        return 'We are here: ';
    }
...

When I run the above, which am looking into using, I get an error on the index method:

Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Argument 1 passed to App\Http\Controllers\TestController::index() must be an instance of App\Models\Admin, string given"

Below works, but I don't need the PrimaryFive injection at the method.

class TestController extends Controller
{
   private $five;
    public function __construct(PrimaryFive $five,Request $request)
    {
        $this->five=$five;
    }

    public function index(PrimaryFive $five,Admin $admin,Request $request)
    {
        dd($request->segments(),$five,$admin);
        return 'We are here: ';
    }
...

Is there a way I can set the constructor injection with a model (which works) and set the method injection as well without having to inject the model set in teh constructor?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire