Laravel路由'/posts/savedPosts'返回NotFound错误求助
访问
/posts/savedPosts时出现NotFound错误排查 问题描述
尝试访问路由/posts/savedPosts时遇到“NotFound”错误,无法定位问题根源。
路由配置(web.php)
Route::get("/posts/saves",[SaveController::class, "savedPosts"])->middleware("auth");
SaveController代码
//Saved the post public function savePost(Post $post) { // Check if the user has saved the specified post $isSaved = auth()->user()->saves()->where('post_id', $post->id)->exists(); if ($isSaved) { // Detach the specified post from the user's saves auth()->user()->saves()->delete($post->id); return redirect()->back(); } else { // Save the post for the authenticated user auth()->user()->saves()->create(['post_id' => $post->id]); return redirect()->back()->with("message", "Post saved successfully"); } } //Show All the Saved Posts public function savedPosts() { // Get All the posts for the current authenticated user $posts = auth()->user()->saves(); dd($posts); return view("posts", ["posts" => $posts]); }
尝试过的无效方法
Route::get("/posts/saves", function () { return "Hello, World!"; });
排查分析
- 路径不匹配:你定义的路由是
/posts/saves,但实际访问的是/posts/savedPosts,两个路径不一致,这是导致NotFound的直接原因。要么修改路由定义为/posts/savedPosts,要么调整访问路径为/posts/saves。 - 路由缓存问题:如果之前生成过路由缓存,修改路由后可能未生效,执行
php artisan route:clear清除路由缓存再测试。 - 路由优先级冲突:检查是否有其他通配符路由(比如
Route::get('/posts/{slug}', ...))定义在这个路由之前,导致请求被拦截。确保当前路由定义在更靠前的位置。 - 控制器命名空间:确认
SaveController的命名空间是否正确导入到web.php中,避免因类找不到导致的路由解析失败。
内容的提问来源于stack exchange,提问作者yassine afaila
相关产品推荐
相关产品推荐

