HTTP request filtering is one of the most important needs for every web application, and we all need to implement that capability extremely properly. That feature is also provided by the Laravel PHP Framework, and this idea is known as "Laravel Middleware."

Check out my article Laravel Crud Example From Scratch to learn about the basic CRUD functionality in Laravel.

Laravel Middleware

Laravel middleware implements some functionality during the request hit on the specific URI, as its name says. We need to put layers between our request and response, just like in clothing. To do that, it offers us a very versatile API.

With just one command, custom middleware may be quickly implemented in Laravel. The specific function's logic must then be written and defined in our application. That's all, everyone. Okay, so let's explore it in greater detail using some instances.

Create a Laravel project

composer create-project laravel/laravel LaravelMiddleware --prefer-dist

Create a single database called laravel middleware in phpMyAdmin. Any name you like can be used.

Edit the.env file in your editor, then add your database credentials there.

Laravel Admin Middleware

Now, determine whether or not the current user is an administrator. So, navigate to the migration file for your users' table and add a new field with the name isAdmin and a boolean data type.

<?php

// create_users_migrations

  public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->boolean('isAdmin')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

Now execute the next command.

php artisan migrate

The Laravel Authentication functionality creation process comes next. Put the following on your terminal by typing it.

Laravel Authentication

php artisan make:auth

The auth scaffold will successfully generate as a result.

Enter the next command to launch the server.

php artisan serve

Make three users now. Visit http://localhost:8000/register to register.

We can do it manually even if we haven't given any people the admin role. But keep in mind that you must offer some sort of interface to grant administrative permissions in the real-time web application.

Here, I'm merely demonstrating how to handle admin middleware after submitting the form.

As a result, for the time being, manually set the database's isAdmin field to one for any user.

Make one basic Laravel Middleware

By entering the following Laravel command, one middleware will be created.

php artisan make:middleware Admin

Go to the directory shown below. application > HTTP > Middleware > Admin.php

As you can see, Laravel has supplied some boilerplate.

You mostly have to manage one task, and that is handle ()

// Middleware Admin.php

  /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

The logic for filtering the request must be written in this function. If it is satisfied, the destination page will be displayed; if not, the login page or another redirect page will be displayed.

In this function, I'm writing just one logic.

/**  Admin.php
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if(auth()->user()->isAdmin == 1){
        return $next($request);
      }
        return redirect('home')->with('error','You have not admin access');
    }

I must now add this route to the app's >> Http >> Kernel.php.

There are two ways to register this route.

  • As an international middleware, you can register.
  • You can sign up as route middleware, a specific route.

Go to the protected $routeMiddleware field since we are registering as a route middleware.

<?php

// Kernel.php

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\Admin::class,
    ];

As you can see, I've included our custom middleware called admin here.

Now, if we want to assign any route to this middleware admin, we can only do so if a valid user is admin; otherwise, it will redirect to the homepage.

Admin-protected route middleware

Create one admin-protected route that will redirect to the home page if the user is not an admin; else, he can access this page.

<?php

// web.php

Route::get('admin/routes', 'HomeController@admin')->middleware('admin');

After the user has signed in, we need to add this link to the home page.

<!-- home.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
  @if(\Session::has('error'))
    <div class="alert alert-danger">
      {{\Session::get('error')}}
    </div>
  @endif
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    <a href="{{url('admin/routes')}}">Admin</a>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

All we need to do is code the admin function in HomeController.

<?php

// HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function admin()
    {
        return view('admin');
    }

}

Make one blade file

Create a single view called admin.blade.php in the views folder's root.

<!-- admin.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ADMIN PAGE</title>
  </head>
  <body>
    WELCOME TO ADMIN ROUTE
  </body>
</html>

Laravel Group Middleware

<?php

// web.php

Route::group(['middleware' => ['admin']], function () {
    Route::get('admin/routes', 'HomeController@admin');
});

Middleware groups allow us to attach a single middleware to several routes. It comes naturally.

If I do not want to expose the Admin links to the general user, I have included a condition that says if the user is authenticated as an admin, we can show him that route else not. However, in this case, I have not included anything of the sort.

I'd like to demonstrate that if you are not an administrator and try to access this route, you will be redirected with a correct notice.

Multiple Middleware in Single Route

We can use two middlewares in one route at the same time.

Route::get('admin/routes', 'HomeController@admin')->middleware(['admin','auth']);

Auth Middleware Provided By Laravel

<?php

// Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

The auth and guest middlewares are concerned with user authentication.

VerifyCSRFToken is another global middleware that protects us against CSRF attacks in every POST request.

If the POST request does not contain a CSRF Token, this middleware throws a TokenMismatchException.

That concludes the Laravel Middleware Example.


Tags

Recommended Posts

View All

How To Integrate Google Maps in Laravel


A number of ways are available through the Google Maps JavaScript API to build maps for web applications.

Laravel where clause with date_format() example


laravel db raw where, laravel where date_format, laravel date_format mysql where, laravel date_format example, laravel where with month

Unlocking the Power of Data Visualizing Laravel App Data with Chartello


Discover the potential of data visualization with Chartello, a Laravel app that helps you unlock insights from your data. Try it now and see the resul...

Laravel 9 Dropzone Image Upload Example Step By Step


The most well-known, free, and open-source library for drag-and-drop file uploads with image previews is Dropzone. I&amp;#039;ll be using Laravel 9 in...

Laravel Where Clause with MySQL Function Example


laravel eloquent where year,laravel eloquent mysql functions,laravel eloquent where clause mysql,mysql function mysql laravel