i have 2 models, User and Department. these two have many to many relation with each other. when i try to relation field to toArray() method inside Model class, i get Maximum stack depth exceeded error.
Department Model :
class Department extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function toArray()
{
$arr = parent::toArray();
$arr['users'] = $this->users;
return $arr;
}
}
User Model :
class User extends Model
{
public function departments()
{
return $this->belongsToMany(Department::class);
}
public function toArray()
{
$arr = parent::toArray();
$arr['departments'] = $this->departments;
return $arr;
}
}
what is the right way to have this kind of JSON output?
/api/departments :
{
"success": true,
"data": [
{
"id": 1,
"caption": "asd",
"status": "active",
"users": []
}
]
}
/api/users :
{
"success": true,
"data": [
{
"id": 1,
"username": "asdasd",
"email": "m@m.m",
"status": "active",
"departments": []
}
]
}
In doing what you're doing you're basically going to create an array that will go on indefinitely.
Firstly, remove the toArray()
methods from both models, there are very few reasons to actually override this method.
To achieve what you want you can simply load the relationships using with() when you need them e.g.
public function show($id)
{
return User::with('departments')->findOrFail($id);
}
If you're using Route Model Binding or you've just already retrieved the model you can use load() (lazy eager loading) instead:
public function show(User $user)
{
$user->load('departments');
return $user;
}
this worked for me :
public function with($id, $relations, $columns = ['*'])
{
$query = $this->model->newQuery();
$query = $query->with($relations);
return $query->find($id, $columns);
}