问题
I have table photos in my database where my images are stored. In one view user can see all of them, but in the other I want only one image to be seen, first one. How to set it so only the first image is displayed, not all of them?
This is my code.
View
@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();
}
回答1:
Solution:
@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
回答2:
In your views you are getting an array.if you use first() in foreach you will get that error.
for example:
@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
So use a php tag in views
<?php $x=$business->photos->first(); ?>
if you use this then it shows only one row
and then bind which value you need that is present in $x variable.
来源:https://stackoverflow.com/questions/36222979/laravel-5-2-show-first-image-from-database