DEV Community

Morcos Gad
Morcos Gad

Posted on

Database Driver Scout - Laravel 9

I heard a lot about Scout when Laravel version 9 was released and about the importance of using it in researching small and medium projects and decided to share it with you after getting this wonderful resource https://www.youtube.com/watch?v=7KbJIBM5VHg that talked about it and also don't forget to go to its docs https://laravel.com/docs/9.x/scout and its minister to go deeper

install Scout via the Composer package manager

composer require laravel/scout
Enter fullscreen mode Exit fullscreen mode

you should publish the Scout configuration file

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Enter fullscreen mode Exit fullscreen mode

add the Laravel\Scout\Searchable trait to the model
It will be searched by fields name and email

<?php

namespace App\Models;

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

class User extends Model
{
    use Searchable;

    public function toSearchableArray()
    {
        // $array = $this->toArray(); 
        // return $array;
        return [
          'name' => $this->name,
          'email' => $this->email,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

The database engine currently supports MySQL and PostgreSQL
To use the database engine, you may simply set the value of the SCOUT_DRIVER environment variable to database, or specify the database driver directly in your application's scout configuration file

SCOUT_DRIVER=database
Enter fullscreen mode Exit fullscreen mode

use it

User::search(request('search'))->paginate();
Enter fullscreen mode Exit fullscreen mode

It should be banned that so far the feature does not work with relationships between tables.
I hope you enjoyed the code that it gives you information on your future projects.

Top comments (0)