Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent setAppends() to entire model collection?

As per https://laravel.com/docs/5.6/eloquent-serialization, one can use setAppends on a model instance to dynamically add any available extra attributes to a model. However, I haven't been able to find a way to do this to a collection of models, aside from looping through the collection.

Is there a smarter way to do this? Like so:

$facilities = Facility:all();
$facilities->setAppends();

Currently the only option would be:

foreach ($facilities as $facility) {
    $facility->setAppends([
        'your_attribute_here'
    ]);
}

EDIT: To clarify, I want to do this dynamically at runtime. The extra properties I'm defining aren't needed everywhere where the model is fetched and can cause extra overhead in large quantities.

like image 500
TheCapeGreek Avatar asked Apr 20 '18 09:04

TheCapeGreek


People also ask

How do you append to a collection?

The elements of a Collection can be appended at the end of the ArrayList using the method java. util. ArrayList. addAll().

What is protected $Hidden in Laravel?

According to http://laravel.com/docs/eloquent, one can Hide Attributes From Array Or JSON Conversion by using a protected $hidden variable in the Model. Great, however when running print_r(User::all()) the encrypted password is sent from server to client inside the User object.

What is append in Laravel?

Appends is for when you want data that is not available in the database on your model.

What is eloquent serialization?

October 5th, 2021. Eloquent Serialize is a Laravel package to serialize and unserialize Eloquent query builder objects.


1 Answers

You can use higher order messages:

$facilities->each->setAppends([
    'your_attribute_here'
]);
like image 56
Jonas Staudenmeir Avatar answered Oct 03 '22 13:10

Jonas Staudenmeir