wohe1
wohe1

Reputation: 775

Laravel 5.7 global middleware is not working

I want to create a middleware in my laravel project to check what type of user is logged in to my website. The idea is that I check whether the user is logged in in the middleware and then set a session variable to a certain value.

This is the middleware:

CheckIfLoggedin.php

use Closure;
use Auth;

class CheckIfLoggedin
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $request->session()->put('loggedin', 'admin');
        }
        return $next($request);
    }
}

I've registered it as global middleware as explained in the docs by adding this line to Kernel.php:

protected $middleware = [
    // ...
    \App\Http\Middleware\CheckIfLoggedin::class,
];

And I check the value of this session variable in my blade template like this:

@if(session('loggedin'))
    <!-- some html code -->
@endif

I know that I can also use this for login verification:

@auth
    <!-- some html code -->
@endauth

but the reason for using this session variable is that I there will be different kinds of members (like member or admin) and I would assign the type of login to that session variable later on, it should then work like this in the blade template:

@if(session('loggedin')=='member')
    <!-- some html code that only members can see -->
@elseif(session('loggedin')=='admin')
    <!-- some html code that only admins can see -->
@endif

Any ideas on why this middleware is not working as I expect it to be? Note that I am fairly new to Laravel though...

Thanks!

Upvotes: 0

Views: 1844

Answers (1)

Kyslik
Kyslik

Reputation: 8385

You need to start a session before you can do any work with it, if you read the stock kernel.php you will see that session is started only in web group (via \Illuminate\Session\Middleware\StartSession::class), so you need to add your own middleware below it.

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::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,
    ],

Note: What I would do is to leverage policies and gates and maybe custom guards but not sessions for this kind of job.

Upvotes: 4

Related Questions