Good day, artisans today We'll talk about the full-text scout search in Laravel 9. You will have learned how the scout elastic search functions from today's tutorial. Using the Laravel/Scout package, we'll acquire elastic search. Let's examine how to integrate elastic search into our Laravel application now.

Table of Contents

  1. Install and Configure laravel/scout
  2. Setup User Model
  3. Create Dummy Records
  4. Create and Setup Controller
  5. Create and Setup blade File
  6. Define Routes
  7. Output

Install and Configure laravel/scout

Start your terminal and type the following command to install Laravel and Scout.

composer require laravel/scout

Launch the command listed below to publish our configuration file after a successful installation.

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

The scout driver must now be specified as the database in our .env file. Put the variable listed below in your .env file. 

SCOUT_DRIVER=database

Setup User Model

Our model must now be set up for elastic search. User.php should be replaced with the codes below.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Scout\Searchable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable,Searchable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function toSearchableArray()
    {
        return [
            'name' => $this->name,
            'email' => $this->email
        ];
    }
}

Create Dummy Records

To test and understand how our built elastic search on our User model behaves, we will now use Tinker to construct some dummy records. I strongly advise you to check out one of my quick tutorials on Tinker if you're new to the program. In order to migrate your tables, use the command listed below.

php artisan migrate

Use the commands listed below to create dummy user records following a successful migration.

php artisan tinker

User::factory()->count(20)->create()

20 new users will be added to your users table.

Create and Setup Controller

In order to display all users or users who are now being searched by our implemented elastic search, we will now develop a controller where we will write our logic. So, run the terminal command below to construct a controller.

php artisan make:controller UserController

Under appHttpControllerUserController.php, a controller will be created. Open the file and insert the codes below.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        if($request->filled('search')){
            $users = User::search($request->search)->get();
        }else{
            $users = User::get();
        }

        return view('users', compact('users'));
    }
}

Create and Setup blade File

In this phase, we'll first construct a blade file named users.blade.php that will display a list of users and an integrated elastic search. Create a file called users.blade.php and add the following scripts to it.

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Scout Full Text Search Tutorial - CodeSolutionStuff</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <h1>Laravel 9 Scout Full Text Search Tutorial - CodeSolutionStuff</h1>

    <form method="GET">
        <div class="input-group mb-3">
            <input
                type="text"
                name="search"
                value="{{ request()->get('search') }}"
                class="form-control"
                placeholder="Search..."
                aria-label="Search"
                aria-describedby="button-addon2">
            <button class="btn btn-success" type="submit" id="button-addon2">Search</button>
        </div>
    </form>

    <table class="table table-bordered data-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        </thead>
        <tbody>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

</body>

</html>

Define Routes

Now we'll build the routes for viewing the users list and where we can use elastic search to get the user we're looking for.

Include the routes below in your web.php file.

routes/web.php

Route::get('users', [App\Http\Controllers\UserController::class, 'index']);

Output

We have our setup ready right now. It's time to review our results. Visit http://127.0.0.1:8000/users right away.


Recommended Posts

View All

How To Create Word Document File In Laravel


In Laravel, use the phpoffice/phpword package to create a word document file. In this example, I&amp;#039;ll show you how to create a word document an...

How To Integrate Google Maps in Laravel


A number of ways are available through the Google Maps JavaScript API to build maps for web applications.

Laravel 9 Dropzone Image Upload Example Step By Step


The most well-known, free, and open-source library for drag-and-drop file uploads with image previews is Dropzone. I&amp;#039;ll be using Laravel 9 in...

Laravel Middleware Tutorial With Example


Laravel middleware implements some functionality during the request hit on the specific URI, as its name says.

Laravel Eloquent Query - Laravel whereKey method


We'll look at the whereKey method in Laravel Eloquent in this post. whereKey is an extremely easy-to-use tool with a lot of potential.