John Davidson

php - MorphMany relationship returning empty array in laravel 8

0 comments
Message:


I'm trying to return the product data with image with Morph relationship


I can save the data, however when I'm retrieving it, the images field has empty value.


Product Model:


protected $fillable=['name', 'description'];

public function images(){
$this->belongsToMany(Category::class);
}

Image Model:


protected $fillable=['imagable_id', 'imagable_type', 'file_name'];

public function imagable(){
return $this->morphTo();
}

Product Controller: So this where I want to retrieve the product with image on it.


public function index(){
return Product::with('images')->get();
}

This controller return only the product data, but it has empty images array field.



My Answer:
To fix this issue, you need to make a few changes in your models and controller.

1. In your Product model, change the relationship method to use `morphMany` instead of `belongsToMany`:
php
public function images(){
return $this->morphMany(Image::class, 'imagable');
}


2. In your Image model, change the relationship method to use `morphTo` instead of `belongsTo`:
php
public function imagable(){
return $this->morphTo();
}


3. In your Product controller, eager load the images relationship using the correct method:
php
public function index(){
return Product::with('images')->get();
}


With these changes, when you retrieve the products, the images should now be included in the response.

Rate this post

5 of 5 based on 2516 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us