Digging Deeper

Full Text Search

Laravel Rest Api fully integrates with Laravel Scout, discover how you can implement this in a few steps.
Be sure you have installed Laravel Scout before going further: https://laravel.com/docs/scout

To be more specific about how it works, Laravel Rest Api will implement a Scout Builder and apply to it the filters, sorts and instructions. After this, it will pass other parameters to the query callback of the Laravel Scout Builder. This allows you to eager load data / aggregates for example.

Be aware that using full text search disable features listed here

Model

Full text search is only implemented on models that are Searchable as given in the Laravel Scout documentation:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
 
class Post extends Model
{
    use Searchable;
}

Resource

Query

Because the builder isn't the same than the search query, you should implement the searchScoutQuery to filter the data you want the user has access to:

UserResource.php
/**
 * Build a "search" scout query for fetching resource.
 *
 * @param \Lomkit\Rest\Http\Requests\RestRequest $request
 * @param \Laravel\Scout\Builder                 $query
 *
 * @return \Laravel\Scout\Builder
 */
public function searchScoutQuery(\Lomkit\Rest\Http\Requests\RestRequest $request, \Laravel\Scout\Builder $query)
    return $query;
}

Fields

Also since you are able to totally change the fields or even create new one with scout. Laravel Rest Api defines a scoutFields methods which is use to validate front-end field for full-text search.

This fields will be used to validate sorts and filters fields.

UserResource.php
/**
 * The scout fields that could be provided.
 *
 * @param RestRequest $request
 *
 * @return array
 */
public function scoutFields(RestRequest $request): array
{
    return ['id'];
}

Instructions

In order to give you full control over the scout exposed instructions since the handle is not the same method, you have a new scoutInstructions method in your resource:

UserResource.php
/**
 * The scout fields that could be provided.
 *
 * @param RestRequest $request
 *
 * @return array
 */
public function scoutInstructions(RestRequest $request): array
{
    return [
        NumberedInstruction::make()
    ];
}

Instructions

For instruction since the queries are not the same you might want to customize the scout part for instructions:

MyInstruction.php
/**
 * Perform the instruction on the scout query.
 *
 * @param array                  $fields
 * @param \Laravel\Scout\Builder $query
 *
 * @return void
 */
public function handleScout(array $fields, \Laravel\Scout\Builder $query)
{
    // do something ...
}

Copyright © 2024