覆盖 routeKeyName 以 slug 不起作用
Overriding routeKeyName to slug not working
这是我的 PostController
中的 show
方法,当我 dd($slug)
从数据库中获取 slug 但当我尝试搜索与那鼻涕虫我得到了 404 | Not Found
。我已经在我的模型中覆盖了我的 routeKeyName
但它似乎仍在使用 id 列获取,因为当我在这一行 $post = Post::findOrFail($slug);
中用硬编码 id 2 替换 $slug
然后我从数据库中获取 post。我不知道我错过了什么。
public function show($slug)
{
//dd($slug);
$post = Post::findOrFail($slug);
return view('single-blog', compact('post'));
}
我的模型Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function getRouteKeyName()
{
return 'slug';
}
}
即使使用不同的数据库字段,您仍在使用路由模型绑定。
From the docs:
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.
所以你的路由变量和你传递给你的控制器方法的字段需要匹配,你需要输入提示:
路线:
Route::get('/posts/{post}', [PostController::class, 'show']);
控制器:
public function show(Post $post) {
这是我的 PostController
中的 show
方法,当我 dd($slug)
从数据库中获取 slug 但当我尝试搜索与那鼻涕虫我得到了 404 | Not Found
。我已经在我的模型中覆盖了我的 routeKeyName
但它似乎仍在使用 id 列获取,因为当我在这一行 $post = Post::findOrFail($slug);
中用硬编码 id 2 替换 $slug
然后我从数据库中获取 post。我不知道我错过了什么。
public function show($slug)
{
//dd($slug);
$post = Post::findOrFail($slug);
return view('single-blog', compact('post'));
}
我的模型Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function getRouteKeyName()
{
return 'slug';
}
}
即使使用不同的数据库字段,您仍在使用路由模型绑定。 From the docs:
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.
所以你的路由变量和你传递给你的控制器方法的字段需要匹配,你需要输入提示:
路线:
Route::get('/posts/{post}', [PostController::class, 'show']);
控制器:
public function show(Post $post) {