Home / Blog /

Filter index resources Laravel Nova

3 years ago

Filter index resources Laravel Nova

On the index page of a Laravel Nova Resource, you may notice that all records are loaded. You would think that returning false from the view function in the policy of the related resource would stop specific resources from appearing on the index page. Unfortunately, this is not the case and requires a special approach.

👀 467 views

To stop certain resources from appearing on the index page, you need to override the indexQuery on your Nova Resource.

/**
 * Build an "index" query for the given resource.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function indexQuery(NovaRequest $request, $query)
{
    return $query->where('user_id', $request->user()->id);
}

The above code would only show the resources that have the same user ID as the current authenticated user.

Besides where constraints, you can also use joins to load related tables and much more. Below is an example I provided to someone on StackOverflow:

public static function indexQuery(NovaRequest $request, $query)
{
    return $query->join('devices', 'devices.id',  '=','works.device_id')
        ->join('device_types', 'device_types.id', '=', 'device_type_id')
        ->join('brands', 'brands.id', '=', 'brand_id')
        ->select([
            'works.*',
            'devices.device_type_id as device_type_id',
            'devices_types.device_name as device_name',
            'devices_types.brand_id as brand_id',
            'brands.brand as brand'
        ]);
}