我想使用slug,但是当我单击并跳转到特定帖子时,404 找不到。
URL运行良好,所以我不知道为什么我看不到 结果。
web.php
Route::get('results/{post}', 'ResultsController@show')->name('posts.show');
post.php
public function getRouteKeyName()
{
return 'slug';
}
ResultsController.php
public function show(Post $post)
{
$recommended_posts = Post::latest()
->whereDate('date','>',date('Y-m-d'))
->where('category_id','=',$post->category_id)
->where('id','!=',$post->id)
->limit(7)
->get();
$posts['particular_post'] = $post;
$posts['recommended_posts'] = $recommended_posts;
return view('posts.show',compact('posts'));
}
表
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image');
$table->unsignedBigInteger('category_id');
$table->string('title');
$table->string('slug');
$table->string('place');
$table->string('map');
$table->date('date');
$table->string('organizer');
$table->string('organizer_link');
$table->timestamp('published_at')->nullable();
$table->text('description');
$table->timestamps();
});
PostsController.php
public function store(CreatePostsRequest $request)
{
//upload the image to strage
//dd($request->image->store('posts'));
$image = $request->image->store('posts');
//create the posts
$post = Post::create([
'image' => $image,
'category_id' => $request->category,
'title' => $request->title,
'slug' => str_slug($request->title),
'place' => $request->place,
'map' => $request->map,
'date' => $request->date,
'organizer' => $request->organizer,
'organizer_link' => $request->organizer_link,
'published_at' => $request->published_at,
'description' => $request->description
]);
result.blade.php
<a href="{{ route('posts.show', [$post->id,$post->slug]) }}" class="title-link">{{ str_limit($post->title, 20) }}</a>
答案 0 :(得分:1)
您已定义模型以使用slug
键进行隐式路由模型绑定。您定义的路由results/{post}
采用1个参数post
。您正在向路由帮助程序传递一个id和一个标签,这使它使用id作为参数:
route('posts.show', [$post->id, $post->slug])
此路由无需传递帖子的ID,您可以对参数使用slug:
route('posts.show', $post->slug);
// or
route('posts.show', ['post' => $post->slug]);