Dec 10, 2019 by Thibault Debatty | 3449 views
https://cylab.be/blog/48/understanding-laravel-middleware-admin-users
In Laravel, a Middleware is basically a piece of code that should be executed for every http request. Middlewares are typically used to:
In this blog post we show how to create a middleware to ensure that only administrators can access admin pages of our web application.
You can create your middleware using artisan:
php artisan make:middleware Admin
Your new middleware will be created in app/Http/Middleware. It has only one method handle($request, $next). This is where you should put your code:
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class Admin
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user() && Auth::user()->isAdmin()) {
return $next($request);
}
return abort('403');
}
}
Your middleware will only be executed if it is registered in app/Http/Kernel.php
There are two possibilities here:
protected $routeMiddleware = [
'admin' => AppHttpMiddlewareAdmin::class,
...
We can now use our new middleware in routes/web.php:
Route::get('admin/users', function() {})->middleware('admin');
Or in your controllers:
class MyController extends Controller
{
public function __construct()
{
$this->middleware('admin');
}
This blog post is licensed under CC BY-SA 4.0