Laravel如果点击显示单一的文章标题



我想做一个博客的帖子,当帖子的标题被点击在单一的帖子应该显示。但当我现在点击一个标题,我得到一个404未找到错误。我为我的错误提前道歉,我刚开始使用laravel

为PostController

/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public function index()
{
$name = 'Mijn posts';
//get data from the te model
$posts = Posts::all();
//dd($posts);
return view('posts.index', compact('name', 'posts'));
}
public function show(Post $slug)
{
return view('posts.post', ['post' => $slug]);
}
}

web.php

Route::get('/posts', [AppHttpControllersPostController::class, 'index'])->middleware('auth');
Route::get('/posts/{slug}', [UserController::class, 'show']);

Post.blade

@extends('layouts.app')
@section('showpost')
<div>
@foreach ($posts as $post)
<h1> {{ $post->title }} </h1>
<p> {{ $post->body }} </p>
@endforeach
</div>
@endsection

我错过了什么?

首先你需要添加一个路由名:

Route::get('/posts/{slug}', [UserController::class, 'show'])->name('post.show');

第二,你需要改变<h1> to <a href="{{route('post.show',$post)}}">

路由模型绑定未收到通知如果你尝试这样做,它将完成

为PostController

/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public function index()
{
$name = 'Mijn posts';
//get data from the te model
$posts = Posts::all();
//dd($posts);
return view('posts.index', compact('name', 'posts'));
}
public function show($slug)
{
$slug = Post::where('slug', $slug)->first();
return view('posts.post', ['post' => $slug]);
}

最新更新