wiwa1978
wiwa1978

Reputation: 2687

Laravel: addressing first item from array in view file

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?

Additional information

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

Answers (2)

Ashly
Ashly

Reputation: 521

Try this -

<img src="{{ $event[0]->images()->filename }}" class="img-responsive" />

This will solve your problem.

Upvotes: 0

cssBlaster21895
cssBlaster21895

Reputation: 3710

Try

<img src="{{ $event->images()->first()->filename }}" class="img-responsive" />

Upvotes: 2

Related Questions