我的数据库中有photos
表,我的图像存储在其中。在一个视图中,用户可以看到所有这些,但在另一个视图中,我只想看到一个图像,第一个。如何设置它只显示第一个图像,而不是所有图像?
这是我的代码。
查看
@foreach($business->photos as $photo)
<img src="{{ url($photo->thumbnail_path) }}" class="img-thumbnail">
@endforeach
ProfileController可
public function profile($id)
{
$user = User::findOrFail($id);
return view('business.profile', compact('user'));
}
Photo.php
public function business()
{
return $this->belongsTo('App\Business');
}
public function baseDir()
{
return 'images/';
}
public function setNameAttribute($name)
{
$this->attributes['name'] = $name;
$this->path = $this->baseDir() . '/' . $name;
$this->thumbnail_path = $this->baseDir() . '/tn' . $name;
}
PhotosController
public function store($id, AddPhotoRequest $request)
{
$business = Business::fidOrFail($id);
$photo = $request->file('photo');
(new AddPhotoToBusiness($business, $photo))->save();
}
答案 0 :(得分:1)
解决方案:
@if(count($business->photos))
<img src="{{ url($business->photos[0]->thumbnail_path) }}" class="img-thumbnail" alt="">
@else
<img src="{{ URL::asset('/img/no-image.png') }}" class="img-responsive" alt="">
@endif
答案 1 :(得分:0)
在您的视图中,您将获得一个数组。如果您在foreach中使用first(),则会收到该错误。
例如:
@foreach($business->photos as $photo)
<img src="{{ url($photo->thumbnail_path) }}" class="img-thumbnail"
alt="">
@endforeach
->here $business->photos holding an array.in that if you use $business->photos->first() .it shows error
所以在视图中使用php标签
<?php $x=$business->photos->first(); ?>
如果你使用它,那么它只显示一行
然后绑定$ x变量中存在的所需值。