Laravel 9 Scout How To Add Full Text Search in Table

Share this Article
Reading Time: 9 minutes
3,083 Views

Inside this article we will see the concept of Laravel 9 Scout How To Add Full Text Search in Table. Article contains the classified information about Laravel 9 Scout function.

Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

Scout is a composer package. To work with full text search feature with scout, we need to install it first inside application.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Migration

We will create a students table using migration and then we seed test data inside it.

Open project into terminal and run this command to create migration file.

$ php artisan make:migration create_students_table

It will create 2022_04_17_031027_create_students_table.php file inside /database/migrations folder. Open migration file and write this following code into it.

The code is all about for the schema of students table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name", 120);
            $table->string("email", 50)->nullable();
            $table->string("mobile", 50)->nullable();
            $table->integer("age");
            $table->enum("gender", ["male", "female", "others"]);
            $table->text("address_info");
            $table->timestamp("created_at")->useCurrent();
            $table->timestamp("updated_at")->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create students table inside database.

Create Model

Back to project terminal and run this command to create model.

$ php artisan make:model Student

It will create Student.php file inside /app/Models folder. This file will help when we generate data using factory and insert into table.

Create Data Factory

Next,

Copy this command and run into terminal to create a factory file.

$ php artisan make:factory StudentFactory

It will create a file StudentFactory.php inside /database/factories folder. Open file and write this following code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Student>
 */
class StudentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            "name" => $this->faker->name(),
            "email" => $this->faker->safeEmail,
            "mobile" => $this->faker->phoneNumber,
            "age" => $this->faker->numberBetween(25, 45),
            "gender" => $this->faker->randomElement([
                "male",
                "female",
                "others"
            ]),
            "address_info" => $this->faker->address
        ];
    }
}

Call Model Factory

Open DatabaseSeeder.php from /database/seeders folder. Load model and factory.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
         \App\Models\Student::factory(100)->create();
    }
}

Concept

\App\Models\Student::factory(100)->create();

It will generate 100 fake rows of student using StudentFactory.php file and save into students table.

Run Data Seeder

Back to project terminal and run this command to run factory to seed fake data.

$ php artisan db:seed

It will generate and save fake data into students table.

Install Scout Package

To install scout, we need to run a composer command. Open up the project terminal and type this command and execute.

Package Installation

$ composer require laravel/scout

While installation of this package, you will get such type of screen over terminal.

After installing Scout, you should publish the Scout configuration file using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your application’s config directory.

Package Configuration Publish

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

Add to .env

Add this line to .env file.

SCOUT_DRIVER=database

Update Model File

Open Student.php from /app/Models folder. Add these following settings for scout search.

Import scout package

use Laravel\Scout\Searchable;

Then,

use Searchable;

Add searchable keys settings,

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

This method will tell the search process that searching will be from the value of name, email and gender. If you add more keys into it then search process will be more flexible.

Here, is the complete code Student.php model file –

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory, Searchable;

    public $timestamps = false;

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

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller StudentController

It will create StudentController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    public function index(Request $request)
    {
        if ($request->filled('search')) {
            $students = Student::search($request->search)->get(); // search by value
        } else {
            $students = Student::get()->take('10'); // list 10 rows
        }

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

Create Template

Create a fie students.blade.php inside /resources/views folder. Open students.blade.php and write this content into it.

<html>

<head>
    <title>Laravel 9 Scout How To Add Full Text Search</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">

        <h3 class="mt-5 mb-5 text-center">Laravel 9 Scout How To Add Full Text Search</h3>

        <form method="GET" class="mb-5">
            <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-primary" 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>
                    <th>Gender</th>
                    <th>Mobile</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($students as $student)
                    <tr>
                        <td>{{ $student->id }}</td>
                        <td>{{ $student->name }}</td>
                        <td>{{ $student->email }}</td>
                        <td>{{ ucfirst($student->gender) }}</td>
                        <td>{{ $student->mobile }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>

</body>

</html>

Add Route

Open web.php file from /routes folder. Add this route and code into it.

//...

use App\Http\Controllers\StudentController;

//...

Route::get('students', [StudentController::class, 'index']);

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL – http://127.0.0.1:8000/students

List all rows with search textbox

List rows by putting a search value i.e ‘Ny

We hope this article helped you to learn about Laravel 9 Scout How To Add Full Text Search in Table in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5