'Laravel 8 call other model relationship in model relationship

enter image description here

I have that relationship, and the main problem is how do I show Product where has relationship with product_image / discounts and render that on the blade?

There my Cart class model :

public function products()
{
    return $this->belongsTo(Product::class, 'product_id','id');
}

There's my product class model :

public function discounts()
{
    return $this->hasMany(Discount::class, 'product_id', 'id');
}

public function images()
{
    return $this->hasMany(ProductImage::class, 'product_id', 'id');
}

public function getProductImage()
{
    return $this->images->image_name;
}

This is both whatdiscount and product_images code to returning relationship

public function products()
{
    return $this->belongsTo(Product::class, 'product_id','id');
}

And how do I show that on my Cart blade? I've use this but still shows error

@foreach($cart as $data)
    @foreach ($data->products as $item)
        <th scope="row">
            <img src="{{ asset('images/'.$item->image->image ) }}"class="border" style="width:120px;" alt="">
        </th>
    @endforeach
@endforeach


Solution 1:[1]

you are trying to get a single value directly from multiple relations.

public function getProductImage()
{
    return $this->images->image_name;
}

You are trying to directly print the image of more than one image.

@foreach($cart as $data)
    @foreach ($data->products as $item)
        <th scope="row">
            <img src="{{ asset('images/'.$item->image->image ) }}"class="border" style="width:120px;" alt="">
        </th>
    @endforeach
@endforeach

It could be like this.

You determine the first image of the product as the main image.

Product Model:

.....
    protected $appends = ["mainImage"];
.....
public function getMainImageAttribute()
    {
        return $this->images()->first()->image_name;
    }

Thus, you can capture the image with the attribute you have defined from within the product.

@foreach($cart as $data)
    @foreach ($data->products as $item)
        <th scope="row">
            <img src="{{ asset('images/'.$item->mainImage ) }}"class="border" style="width:120px;" alt="">
        </th>
    @endforeach
@endforeach

Solution 2:[2]

did you install the pods, Flow the instruction to add cocopods. https://www.algolia.com/doc/guides/building-search-ui/installation/ios/

Create / Update your pod file.

pod 'InstantSearch', '~> 7.1'

then open terminal and run

'pod install'

then open .xcworkspace.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yunus Emre BaloÄŸlu
Solution 2 Sathya Baman