Ad

Inject Models In Laravel's Controllers's Constructors Or Laravel's Controller's Concrete Function

Imagine situation that in laravels constructor(PostController) I need to Inject 3 models: User, Post and Comment.

I have two scenarios:

1) Inject these 3 Models all in controllers constructor and then I use this controllers variables in concrete functions like this: $this->post

2) Inject these models in concrete controller's functions whenever, wherever needed (For example index(Post $post));

which of these two is better practice? In first scenario, in index function I only use $this->post variable, but I also create $this->comment and $this->user because I need them in other functions? but I don't need them in index, so I inject and create them for nothing whenever I call index by addressing index specific route. Isn't that bad? so which of these is better?

Ad

Answer

Generally, When you inject a model in a controller method it means that you're trying to bind a route value to the model. In a simple term, you want laravel to auto-magically fetch that model for you.

On the other hand, when you inject it via the __construct(), you want those models to be instantiated for your use within the class. In simple term, you want Laravel to create a new instance of that model within the class.

Let's go practical:

First situation

//routes

Route::get('/ninjas/{ninja}') //ninja is a number or anything that identifies a model

//Controller

public function index(Ninja $ninja)
{        
    //$ninja will be a resolved model
}

Other situation,

public function __construct(Ninja $ninja)
{        
    $this->ninja = $ninja;
}

public function index($ninja_id)
{        
    $this->ninja->find($ninja_id)
}

As you can see from the above examples, it depends on the use case. That is, if you intend to bind a model to the route then, you inject to controller methods otherwise if you want use your models in a cleaner way then, up to the constructor.

Cheers!

PS: A side note, asking for best practice normally attracts opinionated answer which would make finding a correct answer hard.

Ad
source: stackoverflow.com
Ad