Laravel nova belongsTo filter

Viewed 6208

I have one table championships and one table users. Also I have same models (championship and user).

In one championship may be one main judge, main secretary and judge operator. All of them also are roles in my application and stored in roles table.

I have created new a resource Championship with 3 belongsTo fields. All of them searchable.

        BelongsTo::make('Main judge', 'mainJudge', User::class)
            ->onFormsAndDetail()
            ->searchable(),

        BelongsTo::make('Main secreatary', 'mainSecretary', User::class)
            ->onFormsAndDetail()
            ->searchable(),


        BelongsTo::make('Judge operator', 'judgeOperator', User::class)
            ->onFormsAndDetail()
            ->searchable(),

During the search I need filter query in order to search give only users with same roles.

For example, during the search main judge I have to include next filter into query

select *
from users u
join users_roles ur on u.id = ur.user_id
join roles r on ur.role_id = r.id
where r.alias = 'judge'

I have found some methods into app/Nova/Resource.php such as relatableQuery but how can I use it inside User resource if I have 3 fields with User.

3 Answers

on Championship resource you have to create function with name of relation.

e.g.

public static function relatableMainSecretary(NovaRequest $request, $query)
{
    return $query->where(...);
}

The easiest (and unofficial) way to achieve this is to sniff how request URL is structured. With that in mind you can simply override relatableQuery method in your Nova/User class.

That's how it can be done, please keep in mind that strtolower function is optional and just saves unnecessary hassle with case sensitive typos.

public static function relatableQuery(NovaRequest $request, $query)
{
    $requestSegment = strtolower($request->segment(4));

    if ($requestSegment === 'mainjudge') {
        return $query->where(...);
    }

    if ($requestSegment === 'mainsecretary') {
        return $query->where(...);
    }

    if ($requestSegment === 'judgeoperator') {
        return $query->where(...);
    }
    
    return $query;
}
Related