3

In my inherited code in the Models there's some serious logic and I want to use the Laravel's Dependency Injection in order to load the models as Dependencies into the controller instead of Using the Laravel's provided Facades.

So here's a sample Controller:

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

But Instead of using the Facade User I want to be able to load it as dependency into the controller:


namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;
user App\Models\User

class UserController extends Controller
{

     /**
     * @var User
     */
     private $user=null;

     public function __construct(User $user)
     {
       $this->user=$user;
     }


    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => $this->user->findOrFail($id)]);
    }
}

The reason why I want to do that is because I come from Symfony Background where the Dependency Injection Pattern Is heavily Erdosed. Also Dependency Injection is the Unit Test's best buddy, so I want to be able to unitilize the Dependency Injection that I am familiar with.

So I wanted to know whether I can inject the models where the logic exists in the Controllers Instead of using the Facade Pattern provided by laravel.

1 Answer 1

5

When you register your route, you can use the model binding:

// routes/web.php
Route::get('users/{user}', 'UserController@show');

Then in your controller, you can change your method to:

public function show(User $user)
{
    //
}

Where the $user will be the instance of App\User with the right id. For example, if the url is /users/1, the $user will contain the App\User with id 1.

For more information: https://laravel.com/docs/5.8/routing#route-model-binding

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.