Wai Yan Hein Wai Yan Hein - 3 months ago 26
PHP Question

Unable to inject dependency in Middleware in Laravel 5.2

I am developing a web application using Laravel 5.2. I know Laravel supports dependency injection. I am doing it in middleware. But the dependency is not injected and the instance of the class that is injected is always null. Please see what I have done below.

This is my middleware

class StoreMiddleware
{
private $categoryRepo;

function __construct(CategoryRepo $categoryParam)
{
$categoryRepo = $categoryParam;
}

public function handle($request, Closure $next)
{
$categories = $this->categoryRepo->getTreeViewCategories();
view()->share(['categories'=>$categories]);
return $next($request);
}
}


I declared in kernel like this

protected $routeMiddleware = [
.
.
.
'store' =>\App\Http\Middleware\StoreMiddleware::class
];


I config route like this

Route::group(['middleware'=>'store'],function(){
Route::get('home','HomeController@index');
Route::get('/','HomeController@index');
});


When I access home page, it is giving me this error

FatalThrowableError in StoreMiddleware.php line 20:
Call to a member function getTreeViewCategories() on null


As you can see, it is saying categoryRepo is null and it is not get injected.

This is my getTreeViewCategories() method inside CategoryRepo model.

function getTreeViewCategories()
{
$items = array();
return $items;
}


As you can see, I did nothing in model just to make sure injection is working or not. Please what is wrong with my code? Why is it not working? Please help me.

Answer

You are not assigning the object property here:

function __construct(CategoryRepo $categoryParam)
{
    $categoryRepo = $categoryParam;
}

Change it to this:

function __construct(CategoryRepo $categoryParam)
{
    $this->categoryRepo = $categoryParam
}