Understanding Laravel middleware : admin users

Dec 10, 2019 by Thibault Debatty | 2920 views

Laravel PHP

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:

  • filter access to some parts of the website
  • sanitize the input values in all forms

In this blog post we show how to create a middleware to ensure that only administrators can access admin pages of our web application.

Implementing a middleware

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');
    }
}

Registering a middleware

Your middleware will only be executed if it is registered in app/Http/Kernel.php

There are two possibilities here:

  1. middlewares listed in the array $middleware will be executed for all incoming requests. By default you will find here
  • TrimStrings will remove leading and trailing spaces (trim) in all values submitted using a form
  • ConvertEmptyStringsToNull that converts empty strings to null
  1. middlewares listed in $routeMiddleware will be executed only for selected routes. This is where our admin middleware belongs:
protected $routeMiddleware = [
        'admin' => AppHttpMiddlewareAdmin::class,
        ...

Using route middlewares

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

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept