David
David

Reputation: 2007

Limit 1 photo to display out of many - Laravel 5.2

How would I display one photo for a product, if there are many photos associated with the product. For example, I just need to display 1 photo in the front page, and i don't want to do a carousel. Here is what I have so far:

My Product Images

As you can see, im doing a for-each loop, and it is displaying all images associated with that product, I only want to display one image.

Here is how I'm displaying the images:

@foreach($products->photos as $photo)                   
    <img src="/store/{{ $photo->thumbnail_path }}">
@endforeach

My Controller to display the Product for this page:

class ProductsController extends Controller {


    /**
     * Show all products
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showProducts() {
        // Get all products
        $product = Product::all();

        return view('admin.product.show', compact('product'));
    }

}

My Product Model (shortened):

    class Product extends Model {

    /**
     * One Product can have many photos.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function photos() {
        return $this->hasMany('App\ProductPhoto');
    }

}

And this is how my Products Images Tables look like:

My Images Table

My Products Table

Upvotes: 1

Views: 876

Answers (1)

ceejayoz
ceejayoz

Reputation: 180124

Ditch the @foreach and use first() on the photos collection:

<img src="/store/{{ $products->photos->first()->thumbnail_path }}">

If you want to be able to choose which one's featured, you could add a boolean featured column to the photos table and do something like this:

public function featuredPhoto() {
    return $this->hasOne('App\ProductPhoto')->whereFeatured(true);
}

and:

<img src="/store/{{ $products->featuredPhoto->thumbnail_path }}">

Upvotes: 2

Related Questions