Summer Sale! All accounts are 50% off this week.

mlazuardy's avatar

How To Display "You Need To Login First"

maybe i didnt need to show the code but my question is how to Display " You Need to login first to continue" when The Routes is protected by auth middleware in Login page ? sorry if this question is too easy for you guys. But really help and increase my knowledges

0 likes
9 replies
Snapey's avatar

Showing the user the login page usually lets them know they need to login?

1 like
Sergiu17's avatar

Unauthenticated user can't access the page that is under auth middleware, it automatically redirects the user to /login, but you can change this if you want, in app\Exceptions\Handler.php you could overwrite the unauthenticated function

/**
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
        ? response()->json(['message' => $exception->getMessage()], 401) // <-- YOUR MESSAGE
        : redirect()->guest(route('your-route')); // <-- YOUR ROUTE
}

this function is in parent class, and make sure you import this class at the top.

use Illuminate\Auth\AuthenticationException;
Cronix's avatar

So, you'd just attach a message on the redirect, and then check for and display the message in the login view.

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => $exception->getMessage()], 401)
                : redirect()->guest(route('login'))->with('message', 'You Need to login first to continue');
}

and in the login view with the form

@if (session('message'))
    <div>{{ session('message') }}</div>
@endif 

// form to login
Sergiu17's avatar

@Cronix

redirect()->guest(route('login'))->with('message', 'You Need to login first to continue');

Isn't with() method immediately after route() ? or this works too?

redirect()->guest(route('login')->with('message', 'You Need to login first to continue'));
mlazuardy's avatar

@Cronix really helpful thanks sir @Snapey just too make sure for user why they redirect to login page so i need to show the message

Please or to participate in this conversation.