Reputation: 2687
Staring blind at something simple:
I have events model which contains multiple images. In the view, I only want to post the first image. I'm currently doing the following:
@foreach( $events as $event )
<div class="col-md-3 col-sm-6">
<div class="panel panel-default text-center">
<div class="panel-heading">
@foreach( $event->images as $key => $image )
@if ($key == 0)
<img src="{{ $image->filename }}" class="img-responsive" />
@endif
@endforeach
</div>
</div>
</div>
@endforeach
However, I think there must be easier ways, something in the lines of:
@foreach( $events as $event )
<div class="col-md-3 col-sm-6">
<div class="panel panel-default text-center">
<div class="panel-heading">
<img src="{{ $event->images(){0}->filename }}" class="img-responsive" />
</div>
</div>
</div>
@endforeach
This results in Cannot use object of type Illuminate\Database\Eloquent\Relations\MorphMany as array.
Any ideas how to do this?
Controller code is:
public function index() {
$events = Event::currentEvents()->get();
return view('guest/events/index', ['events' => $events]);
}
Model is:
class Event extends Model
{
protected $table = 'events';
public function scopeCurrentEvents($query) {
$now = Carbon::now();
return $query->where('event_startdate', '<=', $now)
->where('event_closedate', '>=', $now);
}
public function images() {
return $this->morphMany('App\Image', 'imageable');
}
Upvotes: 0
Views: 72
Reputation: 521
Try this -
<img src="{{ $event[0]->images()->filename }}" class="img-responsive" />
This will solve your problem.
Upvotes: 0
Reputation: 3710
Try
<img src="{{ $event->images()->first()->filename }}" class="img-responsive" />
Upvotes: 2