inject model in laravel controllers constructor inject model in laravel controllers constructor laravel laravel

inject model in laravel controllers constructor


You use Dependency Injection - it is very good practice.

According to documentation:Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

namespace App\Http\Controllers;use App\User;use App\Repositories\UserRepository;use App\Http\Controllers\Controller;class UserController extends Controller{    /**     * The user repository implementation.     *     * @var UserRepository     */    protected $users;    /**     * Create a new controller instance.     *     * @param  UserRepository  $users     * @return void     */    public function __construct(UserRepository $users)    {        $this->users = $users;    }    /**     * Show the profile for the given user.     *     * @param  int  $id     * @return Response     */    public function show($id)    {        $user = $this->users->find($id);        return view('user.profile', ['user' => $user]);    }}

In this example, the UserController needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository most likely uses Eloquent to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the UserRepository when testing our application.

Read also about Service Container - it is powerful tool:https://laravel.com/docs/5.6/container


It is a good practice for injecting models in controllers, however, the recommended approach is:

  • Have a use statement at the top of your controller file
  • Implement it in the functions that requires access to the model, i would not recommend you do it in your controller
  • If you have a look at the documentation, you will be able to bind the model directly to your route and eliminate some hassle of Model::find(id) https://laravel.com/docs/5.6/routing#route-model-binding

The constructor approach you presented is recommended in using other classes like repositories, singletons, or whatever functionality you wish to inject, see the docs for more info: https://laravel.com/docs/5.6/container

Hope this helps