Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david19's avatar

Many to Many (Search Select Relation in Datatable)

Hello Team. I created a User Datatable Livewire Component. In the table, i have a search select field. ID and Name works, but not the Roles in the Relationship. Its Many to Many relationship with Roles.

( role_user table ).

If i use only laravel in a blade view, i can fetch easy the roles.

@foreach($users as $user)
   @foreach($user->roles as $role)
      {{ $role->name }}
   @endforeach
@endforeach

That works fine! But now i like use the select box for search in the livewire datatable, and it will not work. I dont find the mistake. Name and ID works great, but not the Relationship Roles. Here is my code function. Many thanks.

User.php

public static function search($search)
    {
        return empty($search) ? static::query()
            : static::query()
                ->whereHas('roles', function ($query) use ($search) {
                    $query->where('name', 'like', '%'.$search.'%');
                })
                ->orWhere('id', 'like', '%'.$search.'%')
                ->orWhere('name', 'like', '%'.$search.'%');
                
                
    }
0 likes
1 reply
PaulMaxOS's avatar

I have got something similar but I'm using ID as value of the select. Then I'm performing a query like so:

$query->whereHas('roles', function($query) use ($roleId) {
    $query->where('role_id', '=', $roleId);
});

The difference is that I'm not digging my way down to the roles table, but staying on the role_user table. I could imagine that this is the issue with your query. You are trying to find the role by name but as you are still in the pivot there is no name.

Please or to participate in this conversation.