Laravel Custom Middleware

610 Views Asked by At

I am trying to achieve this using middleware

web.php

Route::get('/test', 'TestController@index')->middleware('TestLogin');

redirect to /test if session is found

Route::get('/test1', 'TestController@index1')->middleware('TestLogin');

redirect to test1 if session is set

Middleware -TestLogin

public function handle($request, Closure $next)`
    { 
        if($request->session()->get('Username'))
        {
            return redirect()->route(\);
            // what to write here to redirect to the path its being called from

        }
        
        return redirect()->route('login');
        
}

don't want to use default auth middleware

1

There are 1 best solutions below

2
On

Your middleware is suppose to check the login (session), if it is not found then redirect to login page otherwise it should pass the request. Something like this:

public function handle($request, Closure $next)
{ 
    // No login session, redirect
    if(!$request->session()->get('Username'))
    {
        return redirect()->route('login');
    }

    // Pass the request down the rest of pipeline
    return $next($request);       
        
}

You should consider to use built in authentication system in Laravel itself, it will save you lots of code and you can be sure the auth is handled correctly in security point of view.