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);
}
}
protected $routeMiddleware = [
.
.
.
'store' =>\App\Http\Middleware\StoreMiddleware::class
];
Route::group(['middleware'=>'store'],function(){
Route::get('home','HomeController@index');
Route::get('/','HomeController@index');
});
FatalThrowableError in StoreMiddleware.php line 20:
Call to a member function getTreeViewCategories() on null
function getTreeViewCategories()
{
$items = array();
return $items;
}
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
}