Home / Snippets / Laravel Nova Scout Integration with MeiliSearch
Laravel Nova Scout Integration with MeiliSearch cover

Laravel Nova Scout Integration with MeiliSearch

589

2 years ago

0 comments

By default, Laravel Nova searches any available resource with the defined database columns.  Having this as the default option is good enough but for a smarter and typo tolerant search, you will have to integrate Laravel Scout to Laravel Nova.

How to Enable Laravel Scout for Laravel Nova?


To enable the scout driver in Laravel nova with the MeiliSearch driver, you can use the "Searchable" trait available from "Laravel\Scout\Searchable". By using this trait, the associated Nova resource will automatically use Scout when performing searches against the resources.
Imagine you are having a Post model and you want it to be searchable, you can define it as follows.
<?php

namespace App\Models;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory, Searchable;

    // your other codes here
}

How to Customize Scout Searches for Laravel Nova?


To customize the scout search result, you can override the "scoutQuery()" method on the resource you want to customize.
use Laravel\Nova\Http\Requests\NovaRequest;

/**
 * Build a Scout search query for the given resource.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
 * @param  \Laravel\Scout\Builder  $query
 * @return \Laravel\Scout\Builder
 */
public static function scoutQuery(NovaRequest $request, $query)
{
    return $query;
}

How to Limit Scout Result for Laravel Nova?


If you would like to limit the number of search results then you can set the "scoutSearchResults" property.
public static $scoutSearchResults = 200;

How to Disable Laravel Scout for Specific Resource in Laravel Nova?


Otherwise, if you prefer Laravel Scout to be disabled for some of your models, then you can return false to the "usesScout()" method.
/**
 * Determine if this resource uses Laravel Scout.
 *
 * @return bool
 */
public static function usesScout()
{
    return false;
}
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this