Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using session in custom middleware in laravel

I've simple middleware which checks if there is a key in user session.

<?php

namespace App\Http\Middleware;

use Closure;

class CustomAuth
{
    public function handle($request, Closure $next)
    {
        if($request->session()->has('uid')){
            return $next($request);
        }
        else{
            return view('unauth');
        }
    }
}

The problem is that I always get "Session store not set on request." error. Here is my route:

Route::get('home', function () {
        return view('home');
    })->middleware('web', 'CustomAuth');

I've added the middleware in app\Http\Kernel.php in the variable $middleware

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\CustomAuth::class
    ];

I also tried changing my route to this:

Route::group(['middleware' => ['web']], function () {
    Route::get('home', function () {
        return view('home');
    })->middleware('CustomAuth');
});

But this didn't work. Any idea how I can make sure that the session had started, or start it before the middleware is called? I'm using Laravel 5.3

like image 733
Deyan Georgiev Avatar asked Sep 17 '25 20:09

Deyan Georgiev


1 Answers

The L5 middleware consists of 3 "types".

The configuration is found in the Kernel.php file for HTTP requests (typically App\Http\Kernel. There's global middleware which will run for all requests and is declared in $middleware, there's the route group middleware which will run for all requests for a given route group and is declared in $middlewareGroups, by default all routes declared in web.php are considered to be web routes so all the web middleware apply.

The 3rd type is route middleware. These are declared in the $routeMiddleware array in the form "middlewareName" => Middleware::class and can be used in any route e.g.

Route::get("/route", function () { /* route body */ })->middleware("middlewareName");

These run in order global > group > route middleware and the SessionStart middleware runs as part of the group middleware. Any other middleware that needs access to the session will need to be placed after the SessionStart middleware.

Clarification

It occurs to be when re-reading this that this implies that you need to declare the middleware in the $middeware variable to use them. This is not the case, the following syntax is also allowed:

Route::get("/route", function () { 
   /* route body */ 
})->middleware(Middleware::class);

However this syntax will not allow you to provide parameters to the middleware when you use them as you would for example with the authentication middleware when you do auth:api (where api would be a parameter passed to the middleware).

like image 148
apokryfos Avatar answered Sep 20 '25 11:09

apokryfos