La Croix
La Croix

Reputation: 111

Laravel Select the First Row From HasMany Relation

I have 2 table where 1 products have many prodphotos

Database Table Structure

I can retrieve all prodphotos from products with the same id, but my case is listing all the products but only take 1 photo from prodphotos.

Controller :

public function daftarproduk()
{
    $produks = Product::orderBy('created_at', 'desc')->get();

    $select = Product::with('prodphotos')->firstorfail();
    $photo = $select->prodphotos->pluck('photo');

    $kategori = Category::orderBy('created_at', 'asc')->get();

    return view('guest.daftarproduk')
          ->with('produks',$produks)
          ->with('kategori',$kategori)
          ->with('select',$select)
          ->with('photo',$photo);
}

View :

@foreach($produks as $value)
    <div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
        <div class="box-product">
            <div class="img-wrapper">
                <a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
                    <img alt="Product" src="images/gambarproduk/thumb_{{ i dont know what i must throw here to only get first picture }}">
                </a>
            </div>
            <h6><a href="detail/{{$value->id}}/{{str_slug($value->name)}}">{{$value->name}}</a></h6>
        </div>
    </div>
@endforeach

I dont know what function I must use to get the first photo name from $select or $photo from controller. or my foreach logic is wrong? Please help me.

Upvotes: 1

Views: 3172

Answers (1)

chanafdo
chanafdo

Reputation: 5124

Add a featured photo relation with hasOne type to your Product model.

Product model

public function featuredPhoto() {
    return $this->hasOne(PhotosModel);
}

In your controller

public function daftarproduk()
{
    // Get the products with featured image
    $produks = Product::with('featuredPhoto')->orderBy('created_at', 'desc')->get();
    $kategori = Category::orderBy('created_at', 'asc')->get();

    return view('guest.daftarproduk')
          ->with('produks',$produks)
          ->with('kategori',$kategori);
}

View

@foreach($produks as $value)
    <div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
        <div class="box-product">
            <div class="img-wrapper">
                <a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
                    <img alt="Product" src="images/gambarproduk/thumb_{{ $value->featuredPhoto->photo }}">
                </a>
            </div>
            <h6><a href="detail/{{$value->id}}/{{str_slug($value->name)}}">{{$value->name}}</a></h6>
        </div>
    </div>
@endforeach 

Upvotes: 1

Related Questions