Lloyd Banks
Lloyd Banks

Reputation: 36659

Laravel / Eloquent - Difference Between Using toArray() and json_decode to Convert Object to Array

Sometimes when I need to convert an object I get back from an Eloquent model I use

json_decode(json_encode($myObject), false));

I've also used

$myObject->toArray();

I've noticed that the json_decode method doesn't work on objects returned from paginate().

What's the difference in implementation between these two methods?

Upvotes: 0

Views: 758

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22882

The main difference is that toArray() will serialize your nested relationships, only attributes that are visible, it also mutates your attributes and run casts on them.

Something you can check easily by taking a look at the source code for the Eloquent Model, not the Collection. I saved you some time, the code starts here

Upvotes: 2

Related Questions