What is middleware in Laravel and how to create one

Middleware in web applications is the mid-layer found between the HTTP request and the main application logic. It processes incoming requests and executes the code before a controller’s actions.

Create a middleware in Laravel using the command below.

php artisan make:middleware nameOfMiddleware
or
php artisan make:middleware AdminMiddleware

Laravel middleware in a constructor.

public function __construct(User $user)
{
  	$this->user = $user;
  
    $this->middleware(function ($request, $next) {
        $user = auth()->user();
        if ($user) {
          	$this->user = $user;
        }
      
        return $next($request);
    });
}

Another example of using the Laravel middleware.

Route::get('/profile', function () {
    //
})->middleware('auth');

A custom middleware in Laravel 8.

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class EnsureUserHasRole
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }
 
        return $next($request);
    }
 
}

Another example for a custom middleware Laravel 8.

Route::put('/post/{id}', function ($id) {
    //
})->middleware('role:editor');