Reputation: 165
So this just happend to me. I have 3 models that have a relation with eachother. My schema is like this:
-- RollingStocks
-- Users
-- Tasks
My models have a relationship with eachother:
RollingStock.php
public function task()
{
return $this->hasMany(Task::class);
}
User.php
public function task()
{
return $this->morphMany(Task::class, 'projectleader');
}
Task.php
public function RollingStock()
{
return $this->belongsTo(RollingStock::class);
}
public function projectleader()
{
return $this->morphTo();
}
In my User model I have set the 'password' and 'remember_token' as $hidden
which looks like this:
User.php
protected $hidden = [
'password', 'remember_token',
];
With this little introduction, I will now bring you to my problem. When I fetch in my RollingStocksController all tasks WITH the projectleaders with the following query, the results include the 'hidden' fields in the User model (as projectleader) as well.
$rollingStock = RollingStock::with('task.projectleader')->find($id); // ID matches the ID of the RollingStock I'm trying to fetch)
If I die and dump (dd()
) the object has it's relations, BUT then the fields 'password' and 'remember_token' from the User model
are vissible and printable to the screen if I loop through the object.
Is there a way to hide the fields, even if the model is (eager) loaded as a relation?
Upvotes: 1
Views: 1882
Reputation: 14520
$hidden
only hides fields when the result is returned as JSON. It is easy to forget, but the section of the docs is titled "Hiding Attributes From JSON".
In your controller, try:
return $rollingStock;
Laravel will convert that to JSON, and your hidden fields will not show up. Change it to:
dd($rollingStock);
and they will appear, as the result is not JSON, just a dumped variable.
Upvotes: 3