Laravel未登录访问仪表盘时,如何在登录页显示指定提示消息?
Hey there! I get it—you’ve got the redirect working for unauthenticated users trying to access the dashboard, but that notification message just won’t show up using the $errors approach. Let’s break down why that’s happening and how to fix it.
Why Your Current Approach Isn’t Working
The $errors variable in Laravel is primarily tied to form validation errors. When you redirect without triggering a form submission or explicitly passing errors to the session, that variable won’t have your custom message. So we need a different way to flash the message to the login page.
Method 1: Use Session Flash Messages (Simplest Approach)
This is the most straightforward way to pass a one-time message to the login page.
Update Your Middleware
In the middleware that handles the unauthenticated redirect (usuallyapp/Http/Middleware/Authenticate.php), modify the redirect logic to include a flash message:protected function redirectTo($request) { if (! $request->expectsJson()) { // Flash the message to the session return redirect()->route('login')->with('loginNotice', 'please login to see this page.'); } }Display the Message in Your Login View
In your login blade file, add this snippet where you want the message to appear:@if(session('loginNotice')) <div class="alert alert-warning"> {{ session('loginNotice') }} </div> @endifThe
session()helper grabs the flashed message, and it’ll disappear after the next request (perfect for one-time notifications).
Method 2: Force the Message Into the Errors Bag (If You Prefer Using $errors)
If you really want to use the $errors variable like you originally tried, you can explicitly pass the message to the errors bag using withErrors():
Modify Middleware Redirect
protected function redirectTo($request) { if (! $request->expectsJson()) { return redirect()->route('login') ->withErrors(['loginpermission' => 'please login to see this page.']); } }Keep Your Original View Code
Now your existing line should work:{!! $errors->first('loginpermission', ':message') !!}Just make sure that your login route is correctly named (
route('login')) and that the middleware is properly applied to your dashboard routes.
Quick Troubleshooting Checks
- Double-check that your middleware is assigned to the dashboard routes in
routes/web.php(usually via theauthmiddleware group). - Ensure session storage is working correctly (Laravel uses file-based sessions by default, so make sure
storage/framework/sessionshas proper permissions). - If you’re using a custom login controller, verify that it’s not overriding the session messages somehow.
That should get your notification showing up every time an unauthenticated user tries to access the dashboard!
内容的提问来源于stack exchange,提问作者Nilesh Paikane

