I've been running into some issues with Laravel's middleware. Let me tell you the basic idea of what I'm trying to accomplish:
Registered users on the site will have one of four roles:
- Student (default): can access 'index' and 'show' views
- Approver: can access previous, plus 'overview', 'update'
- Editor: can access previous, plus 'create', 'edit' and 'store'
- Admin: can access everything
fyi: 'overview' is sort of an index view, but only for approver role and higher
What would you guys suggest is the best way to go about doing this? This is what I've done so far, but it doesn't seem to work:
Kernel.php
protected $middlewareGroups = [
...
'approver+' => [
\App\Http\Middleware\Approver::class,
\App\Http\Middleware\Editor::class,
\App\Http\Middleware\Admin::class,
],
];
protected $routeMiddleware = [
...
'student' => \App\Http\Middleware\Student::class,
'approver' => \App\Http\Middleware\Approver::class,
'editor' => \App\Http\Middleware\Editor::class,
'admin' => \App\Http\Middleware\Admin::class,
];
Http\Middleware\Admin.php
public function handle($request, Closure $next)
{
if (Auth::check())
{
if(Auth::user()->isAdmin())
{
return $next($request);
}
}
return redirect('login');
}
The 'User' Eloquent model:
public function isAdmin()
{
if($this->role_id === 4)
{
return true;
}
else
{
return false;
}
}
I've done the exact same in the Approver and Editor middleware files, and in the isApprover and isEditor functions in the User model, only edited the checked value in the if-statement to 2 and 3 respectively.
Finally, here's what I've done in my routes\web file:
Route::get('scholen', 'SchoolsController@index');
Route::get('admin/scholen/overzicht', 'SchoolsController@overview')->middleware('approver+');
Route::get('admin/scholen/maken', 'SchoolsController@create')->middleware('approver+');
Route::post('scholen', 'SchoolsController@store')->middleware('approver+');
Route::get('scholen/{id}', 'SchoolsController@show');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController@edit')->middleware('admin');
Route::patch('admin/scholen/{id}', 'SchoolsController@update')->middleware('admin');
Route::delete('admin/scholen/{id}', 'SchoolsController@destroy')->middleware('admin');
It isn't all exactly on point yet, but I got stuck since when I log in as a user with Approver rights and try to access the schools overview, it redirects me back to the home page.
In general, it just feels like I'm working much too chaotically and not right at all, could somebody give me advice on how to do it more efficiently?
Thank you very much in advance!