Update: Laravel 5.1.11 and newer now with built-in Authorization . This is a much more friendly Laravel and will always be in good condition. Use it whenever possible
You are using middleware incorrectly. There are a lot of Laravel 4 materials in the documents for Entrust, so you have to be selective about what you use from there. Middleware should not set routeNeedsRole . Actually routeNeedsRole in my opinion is not suitable for L5. Here's how I do it:
Create new middleware with
php artisan make:middleware AuthAdmin
Now in the newly created application /Http/Middleware/AuthAdmin.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Guard; class AuthAdmin { protected $auth; public function __construct(Guard $auth) { $this->auth = $auth; } public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } else if(! $request->user()->hasRole('superadmin')) { return abort(404);
This will do the same as the auth middleware, but if they are already logged in and do not have the "superadmin" role, they will get 404.
Next, we need to add middleware for routing. Do it in app/Http/Kernal.php :
protected $routeMiddleware = [ ..., 'superadmin' => 'App\Http\Middleware\AuthAdmin', ];
This allows you to add middleware to the controller. Now let's do it. In the controller, we do this in the constructor:
public function __construct() { $this->middleware('superadmin'); }
This will add middleware to the entire controller. You can be specific regarding routes if necessary, but for your case I would suggest that we need an entire secure controller.
Let me know if you need more help.
Note. . It would be ideal if AuthAdmin first ran the "auth" middleware instead of copying the code, but I donโt know how to do this from the middleware, and we donโt do you need to do middleware => ['auth', 'superadmin'] instead of 'superadmin' . If we did not copy the "auth" code, we would try to get ->hasRole() from null, which would receive an error.