为什么要在eloquent中使用appends
讲真话的最大好处就是:不必记得自己讲过什么。
Eloquent has a convenient feature called Accessors – you can define your own custom fields on top of existing in the database table. But then there’s an Eloquent property $appends – should we use it or not? And what’s the difference?
First – how Accessors work
For those who don’t know or have forgotten: for example, if you have User model and fields first_name and last_name in the DB table, then you can create a function in app\User.php:
1 | function getFullNameAttribute() { |
Then you have access to property full_name (in the function name it’s CamelCase, and the property name is with underscoresd, for example like this:
1 | ho User::find(1)->full_name; |
But here’s the thing – if you just return User object, it won’t contain full_name:
1 | dd(User::find(1)->toJSON()); |
The result would look something like this:
1 | { |
Here’s where $appends comes in
Now this is the trick – in your User model you can add $appends attribute and list the fields that would automatically be appended:
1 | class User extends Model |
Now that attribute will be automatically added to the previous JSON:
1 | { |
https://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/