php - how to get unique (distinct) values from many to many relationship in laravel blade?

I have 3 model : User , Ticket , Tag . relationships are like :

ticket model

public function Users()
{

    return $this->belongsTo('App\User');
}

public function Tags()
{

    return $this->belongsToMany('App\Tag');
}

user model:

 public function Tickets()
{

    return $this->hasMany('App\Ticket');
}

tag model

 public function Tickets()
{
    return $this->belongsToMany('App\Ticket');
}

I want to get all tags of tickets of a specific user. in distinct way (with no repetition) in controller I have this code :

public function usersTags()
{

    $tickets = Auth::user()->Tickets()->get();
     return view('test' , compact('tickets'));

}

and in my blade I have these :

 @foreach ($tickets as $ticket)
            @foreach ($ticket->tags as $tag)
                    <ul>
                        <li>
                                {{$tag->title}}

                        </li>
                    </ul>
              @endforeach
    @endforeach

these codes give me all tags but with repetition of tags . can anybody help me plz ?

Answer

Solution:

use unique method

@foreach ($tickets->map(function($t){return $t->tags;})->unique('id') as $tag)
    <li> {{$tag->title}} </li>
@endforeach

Answer

Solution:

You can group tickets by name or id by like this

public function usersTags()
{
 $tickets = Auth::user()->with(['Tickets'=> function($query) {
    $query->groupBy('name'); //or whatever column you want to group 
 }])->get();

 return view('test' , compact('tickets'));
}

Source