young_artisan's avatar

How do I add append attribute to collection when I called methods.

Hi Guys, I want to add an attribute to Model only when I called id when I append it to the array always return attribute but I want only when called it returning.

//User Model
public function getLinksAttribute()
    {
        return [
            'equipment_url' => route('profile', $this->id),
        ];
    }

//User Controller
$users = Users::get();
foreach($users as $user) {
    $user->append('links');
}

I want to remove foreach and call links on $users instead of each $user.

0 likes
5 replies
lostdreamer_nl's avatar

If youre using laravel 5.5 you van do this:

$users->each->append('links');
9 likes
crnkovic's avatar
// User.php
protected $appends = ['links'];

public function getLinksAttribute() { ... }
5 likes
rawilk's avatar

@crnkovic That would work too, but I think he only wants that attribute to be appended in a specific request.

2 likes

Please or to participate in this conversation.