【发布时间】:2015-10-26 17:28:01
【问题描述】:
当我创建一篇文章时,我可以附加一张图片作为缩略图。一切正常,图片上传到 img 目录,图片路径添加到 images 表中,并且 images 表中的 article_id 与正在创建的文章的 id 相关。
在我的 RouteServiceProvider 中,我有这个:
public function boot(Router $router)
{
$router->bind('blog', function($id)
{
return Article::with('images')->findOrFail($id);
});
$router->bind('tags', function($name)
{
return Tag::where('name', $name)->firstOrFail();
});
parent::boot($router);
}
在我看来,我有:
@foreach ($articles as $article)
<h2><a href="/blog/{{ $article->id }}">{{ $article->title }}</a></h2>
<p>{{ $article->body }}</p>
<small>Posted on {{ date('F d, Y', strtotime($article->created_at)) }} by {{ $article->user->name }}</small>
<img src="{{ $article->images }}">
@endforeach
{{ $article->images }} 返回一个集合,例如:
[{"id":17,"path":"img\/image2.jpg.jpg","article_id":49,"created_at":"2015-10-25 01:57:49","updated_at":"2015-10-25 01:57:49"}]
而且对于foreach语句中的每一个文章图片基本上都是重复上面的操作,除了id、article_id、path等都发生了变化。
{{ $article->images->path }} 返回错误“尝试获取非对象的属性”。如何在我的 routeserviceprovider 中编写代码,以便它只获取一张图像而不是一个集合,这样我就可以使用{{ $article->images->path }} 而不会出错?
【问题讨论】: