Hey @jalafel. Middleware, most definitely middleware. I'm using Entrust to do the same thing. My middleware (CheckForRole) looks like this:
namespace App\Http\Middleware;
use Closure;
class CheckForRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$roles = array_slice(func_get_args(), 2);
if (auth()->check() && auth()->user()->hasRole($roles))
{
return $next($request);
}
return redirect('/');
}
}
And I call it in my controller (along with the auth middleware):
/**
* Call in the middleware to be used in this Controller
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('checkForRole:admin,fieldtech');
}
In this example, I'm cool with either the "admin" or the "fieldtech" roles having access, so I send both arguments through. Btw, my middleware above is not using "argument unpacking" like I would prefer because, for this application, I am unfortunately deploying to a box running PHP 5.5.9. If you're deploying to something running PHP => 5.6, you can use argument unpacking like the cool kids do. That would look like this:
namespace App\Http\Middleware;
use Closure;
class CheckForRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, ...$role)
{
if (auth()->check() && auth()->user()->hasRole($role))
{
return $next($request);
}
return redirect('/');
}
}
I hope this helps.
from : https://laracasts.com/discuss/channels/laravel/using-entrust-to-filter-routes/replies/85859
沒有留言:
張貼留言