Search code examples
phplaravellaravel-5.7

How to use different optional middlewares for same route using same method


I have a problem in applying different middlwares on the same / route. For example

In my project I have used url()->previous() it is because if a user is not logged in for some pages then he/she has to be logged in after few searches or visiting few pages. So when the user logged In then that user has to be redirected back to the previous url.

Actually / this route has few services which are available for whether user is logged In or not. But after logging in, I want to check if the user is admin then he has to be restricted because it's a frontend application. But Whenever I logged in it redirects me to / route because of url()->previous() and I can't apply my middleware on this route because it's a guest route not auth. So the actual question is, How can I make this route optional for multiple middlewares ? Or any other suggestion will be appreciated. Thanks

Route

Route::get('/', 'HomeController@index')->name('home')->middleware('usertype');

Middleware

public function handle($request, Closure $next)
{
    if (auth()->check() AND auth()->user()->type != 1) {
        return $next($request);
    }
    auth()->logout();
    return redirect(route('login'))->with('error','Admin can not login to frontend.');
}

AuthenticatesUsers.php

public function showLoginForm()
{
    if(!session()->has('from')){
        session()->put('from', url()->previous());
    }
    return view('auth.login');
}

protected function authenticated(Request $request, $user)
{
    Session::put('name',$user->userDetail);
    return redirect(session()->pull('from',$this->redirectTo));
}

Solution

  • Well after uploaded my question yesterday, I didn't receive any answer yet. But what I have done for this scenario let me share with you, if anyone can get help from or anyone can assist me more clearly about it.

    Route

    Route::get('/', 'HomeController@index')->name('home'); //removed middleware
    

    AuthenticatesUsers.php

    protected function authenticated(Request $request, $user)
    {
       //If the user is admin he can't login to frontend application
        if ( $user->type == 1){
            auth()->logout();
            return redirect(route('login'))->withError('Admin can not login to frontend.');
        }
    
        session()->put( 'name', $user->userDetail);
        return redirect( session()->pull( 'from', $this->redirectTo ) );
    }
    

    I don't know if it is the best way, but I have done this way for now without using any middleware