I'm using laravel 8, trying to retrieve data from related models which returns empty arrays except for the parent model.
I have 4 models
- Product (Parent)
- Product_categories
- Product_attributes
- Product_photos
I'm fetching the data like this
$product = Product::select('name', 'description', 'price')
->with(['categories' => function($query){
$query->select(['category_id']);
}, 'attributes' => function($query){
$query->select(['attribute_key',
'attribute_value']);
}, 'photos' => function($query){
$query->select(['photo_path']);
}])
->find($id);
return response()->json([$product]);
Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name',
'user_id',
'description',
'price',
'discount',
'status'
];
/**
* Get the photos of the product.
*/
public function photos()
{
return $this->hasMany('App\Models\Product_photos');
}
/**
* Get the attriutes of the product.
*/
public function attributes()
{
return $this->hasMany('App\Models\Product_attributes');
}
/**
* Get the categories of the product.
*/
public function categories()
{
return $this->hasMany('App\Models\Product_categories');
}
}
And this is the response I'm getting
[
{
"name": "Fendi FF motif zip-up hoodie",
"description": "sample description",
"price": 480,
"categories": [],
"attributes": [],
"photos": []
}
]
Any help would be appreciable