What is middleware in laravel and how to create one

The middleware in web applications is the mid-layer between the HTTP request and the application logic. The middleware process incoming requests and execute the code before the controller’s actions.

Create middleware in Laravel using following command.

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

Laravel middleware in 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 use of laravel middleware

Route::get('/profile', function () {

Custom middleware laravel 8

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

custom middleware laravel 8

Route::put('/post/{id}', function ($id) {

Leave a Comment