Laravel未登录用户点击创建帖子链接后登录跳转异常求助
Hey there! Let's sort out that issue with your "Create Post" link for unauthenticated users. I'll walk you through the most common fixes step by step:
1. First, Protect Your Create Post Route
The most likely culprit is that your post.create route isn't guarded by Laravel's authentication middleware. Without this, unauthenticated users can hit the create post page directly, which might throw errors if your view uses authenticated-only data (like Auth::user()).
Update your routes/web.php to add the auth middleware to the route:
Route::get('/post/create', [PostController::class, 'create']) ->name('post.create') ->middleware('auth');
This middleware will automatically redirect unauthenticated users to the login page, and it will add an intended parameter to the login URL so Laravel knows where to send them after successful login.
2. Ensure Login Redirects to the Intended Page
If you're using Laravel's default authentication scaffolding (like the built-in LoginController), it should handle the intended redirect automatically thanks to the AuthenticatesUsers trait. But if you've customized your login logic, make sure you're using redirect()->intended() instead of a fixed redirect.
For example, in your custom login method:
if (Auth::attempt($credentials)) { // Redirect to the create post page if that's where the user was heading return redirect()->intended(route('post.create')); }
The intended() method prioritizes the URL the user was trying to access before login, falling back to the route you pass if there's no intended URL.
3. Optional: Optimize the Link for Guest Users
To avoid any confusion, you can conditionally show the link or a login prompt based on the user's authentication status in your Blade template:
@auth <a href="{{ route('post.create') }}">Create Post</a> @else <a href="{{ route('login') }}">Login to Create Post</a> @endauth
This way, guest users are directed straight to login, and Laravel will still send them to the create post page after they sign in thanks to the middleware's intended redirect.
If you're still seeing an error, feel free to share the specific exception message or your route/login code, and we can dig deeper!
内容的提问来源于stack exchange,提问作者user9297268

