Search code examples
phplaraveleloquenteloquent-relationship

Get first image for each product


I try to get latest 10 products with its images but only the first image so that is what i try

$newProducts = \App\Product::latest()->with(['images', function($el){

   $el->first();

}])->with('category')->take(10)->get();

but it gives me this error

mb_strpos() expects parameter 1 to be string, object given

it has a morph relation between product and image

Product Model

class Product extends Model {
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

Image Model

class Image extends Model {
    public function imageable()
    {
        return $this->morphTo();
    }
}

Solution

  • The above solutions are all good. I personally prefer a different solution that I think is gonna be ideal.

    I am gonna define a different relationship for a product:

    class Product extends Model {
        public function images()
        {
            return $this->morphMany(Image::class, 'imageable');
        }
    
        public function firstImage()
        {
            return $this->morphOne(Image::class, 'imageable');
        }
    }
    

    So you can access the first image directly or eager load the relationship:

    $product->firstImage;
    
    $product->load('firstImage');
    
    Product::with('firstImage');
    

    Just FYI, I learnt about this and other useful database tricks from Jonathan Reinink in Laracon Online 2018.