简体   繁体   中英

Fetch first image from foreign key table Laravel

Reference: Fetch first image from foreign key table but this time in Laravel.

I started playing with Laravel and I want to take first image from every post and show these in my blade.

$secondpost = DB::table('posts')
        ->orderBy('id', 'desc')
        ->skip(1)
        ->take(8)
        ->get();

foreach ($secondpost as $spost)
$secondph = DB::table('post_images')
        ->select('filename')
        ->where('post_id', $spost->id)
        ->limit(1)
        ->get()
        ->pluck('filename');

return view ('pages.index', compact('firstp', 'fph', 'secondpost', 'secondph'));
<div class="row">
 @foreach ($secondpost as $secondp)
 <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
  <div class="row">
   @foreach ($secondph as $sph);
    <img src="{{url($sph)}}" class="imgpost" alt="">
   @endforeach
    <div class="bottomleft">
      <p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
      <p class="ab-desc">{{$secondp->pret}} Eur</p>
    </div>
    </div>
   </div>
 @endforeach
</div>

This code load only one image for every img src. Post_id is foreign key for posts table id.

There are few things you need to confirm.

  1. You have created models for the table like Post for posts table and PostImages for post_images table. If not, follow the documentation. https://laravel.com/docs/5.8/eloquent

  2. You have created the hasMany relationship in your post model with post_images . Like:

In Post model.

/**
* Get the images for the post.
*/
public function images()
{
    return $this->hasMany('App\PostImage');
}
  1. Then change in your controller to use early loading, Like:

$secondpost = \App\Post::with("images")
        ->orderBy('id', 'desc')
        ->skip(1)
        ->take(8)
        ->get();

And now the view looks like:

<div class="row">
 @foreach ($secondpost as $secondp)
 <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
  <div class="row">
    @php
        $image = $secondp->images->first();
    @endphp
    <img src="{{url($image->filename)}}" class="imgpost" alt="">
    <div class="bottomleft">
      <p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
      <p class="ab-desc">{{$secondp->pret}} Eur</p>
    </div>
    </div>
   </div>
 @endforeach
</div>

Solution: 2

You can create another relationship with hasOne to get a single image like:

// In your Post model.

/**
* Get the default image for post.
*/
public function default_image()
{
    return $this->hasOne('App\PostImage')->orderBy("id");
}

Make change in controller to use ->with("default_image") .

And in view you can just use like:

    $secondp->default_image->filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM