gileneusz
gileneusz

Reputation: 1485

Laravel - how to make nested users unique

before I will start really hating php and laravel, I'll ask for help

I'm trying to make unique values of users that are part of my offer collection.

This collection is done by relation on users model:

public function users(){
    return $this->belongsToMany(User::class, 'messages', 'offer_id', 'from');
}

And in controller:

    $user_id = auth()->user()->id;
    $offers = Offer::where('user_id', $user_id)->orderBy('created_at','desc')->get();
    foreach ($offers as $offer)
    {
        $offer->users;
    }
    return $offers;

This is somehow (?) giving me right result with nested 'users' inside my offer collection.

offer_title : (...)

users : Array(3) 0 : {…} 1 : {…} 2 : {…}

And this is correct result, except - users are duplicating - because one user can send multiple messages. This is why I'm trying to make them unique this way:

    foreach ($offers as $offer)
    {
        $offer->users = $offer->users->unique()->values()->all();
    }
    return $offers;

but this is not working at all. I've tried many configurations. How can I fix it?

Upvotes: 0

Views: 288

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

$offer->users sets an attribute, you have to use setRelation():

$offer->setRelation('users', $offer->users->unique());

Also, you should use eager loading to improve the performance:

$offers = Offer::where('user_id', $user_id)
    ->orderBy('created_at', 'desc')
    ->with('users')
    ->get();

Upvotes: 2

Related Questions