当我的 laravel 应用程序中单击博客文章上的"显示更多"按钮时,如何按其 ID 显示特定博客文章?



我正在尝试建立一个小型的Laravel应用程序,在那里我有博客文章,当我点击show more时,我会从它的特定ID显示博客。

这是我的路线:

Route::get('blog', [BlogController::class, 'show']);
Route::get('blog-single/{blog}', [BlogController::class, 'showMore']);

博客单路由中的{blog}段塞应该将id作为showMore方法中的参数,并从Blog模型中找到具有匹配id的blog,正如我在这里添加的那样。

namespace AppHttpControllers;
use AppModelsBlog;
use IlluminateHttpRequest;
class BlogController extends Controller
{
public function show() {
return view('blog', [
'blogs' => Blog::take(5)->latest()->get(),
]);
}

public function showMore($id) {
$blog = Blog::find($id);
return view('blog-single', [
'blog' => $blog,
]);
}
}

我的博客在blog.blade.php中,它们是从数据库中动态获取的,如BlogController:中的show方法所示

<div id="body">
<h1><span>blog</span></h1>
<div>
<ul>
@foreach($blogs as $blog)
<li class="blog-post">
<a href="blog-single" class="figure">
<img src="{{asset('/storage/app/public/product/stach2.jpg')}}" alt="">
</a>
<div>
<h3>{{$blog->title}}</h3>
<p>{{$blog->body}}</p>
<a href="blog-single{{'/'}}{{$blog->id}}" class="more">read this</a>
</div>
@endforeach
</ul>
</div>
</div>

我被路由到blog/blog-single/$id,但它也显示了一个404页面。我不确定问题出在哪里。

错误是因为href将添加当前url。

所以改变这条线

<a href="blog-single{{'/'}}{{$blog->id}}" class="more">read this</a>

而不是使用

<a href="{{url('blog-single/',[$blog->id])}}" class="more">read this</a>

也更好地创建路线名称,如下面的

Route::get('blog-single/{blog}',[BlogController::class,'showMore'])->name('blogSingle');

然后在刀片文件中

<a href="{{route('blogSingle',$blog->id)}}" class="more">read this</a>

最新更新