vincenzoraco's avatar

Eloquent Serializing To Arrays Not Working

Hi guys I have a weird problem with my Laravel application.

I am trying to use eloquent serializing from an eloquent model. If I do this:

$action = App\Action::with(‘User’)->first();
return $action->toArray();

It returns me just the array of the Action model. It should give me the all relation with User. If I do this instead:

$action = App\Action::with(‘User’)->first();
return $action;

It returns the all eloquent model with the relation with User. So if I do $action->user->email it returns the user email. I did this test to be sure the relationship is working.

I do not have now any ideas of why the function toArray() doesn't return the relation as well. I inserted the all User columns in the $visible variable as well, to make sure anything is being left out, but unfortunately still the same result.

What can be the problem? Is there a setting that I should know? In the documentation doesn't tell anything about, just about the $visible variable.

0 likes
5 replies
jeffdavis's avatar

What is the relation between user and action?

vincenzoraco's avatar

return $this->belongsTo('App\User');

So I have auser_id column in the Action table which is connected to the User table and it works well!! The only problem is that is doesn't serialize the eloquent model using ->toArray() method.

Is there something I should know? The doc says:

Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON/ARRAY representation. All other attributes will be hidden when the model is converted to an array or JSON/ARRAY.

I don't why it's hiding the all User model, since I made the all columns 'visible'

jeffdavis's avatar
Level 5

I tested this out. I had to add 'user' to the $visible array on the Action model. Then it worked fine.

1 like
vincenzoraco's avatar

For god sake!!! You solved me a huge problem!!!

When hiding relationships, use the relationship's method name, not its dynamic property name.

I didn't know it should in the $visible property, but only in the $hidden..

Thank you mate! You are amazing!

1 like

Please or to participate in this conversation.