Laravel 9 Algolia Scout Full Text Search Tutorial Example

This Laravel Algolia Scout guide will demystify how to build a full-text search module in the Laravel app using the Algolia Scout package.

Building a full-text search functionality doesn’t require a pearl of wisdom.

To create a full-text search in Laravel, you will need fewer ingredients, a laravel application, a connection to the database, a controller file and a blade view file, and most importantly, the Algolia Scout package that’s all you need.

In this Laravel Algolia Scout example, we will tell you how to process every ingredient to form the quick, responsive, and agile full-text search in laravel.

Let us know more about Laravel Scout, and it’s a powerful driver-based eloquent package that helps you develop super-fast fast-text search combining with your laravel models.

Scout offers a resilient ecosystem to keep search indexes in sync with your model records. There are two types of drivers mainly brought in action by Laravel Scout, Laravel Scout drivers, and Laravel Scout metasearch.

How to Create Full Text Search in Laravel 9 using Scout Algolia

  • Step 1: Download New Laravel App
  • Step 2: Connect to MySQL Database
  • Step 3: Add Algolia and Scout in Laravel
  • Step 4: Get and Add Algolia Keys in Laravel
  • Step 5: Create Model & Migration Files
  • Step 6: Generate + Set Up Controller
  • Step 7: Register New Routes
  • Step 8: Setting Up Laravel Blade View
  • Step 9: View + Test App

Download New Laravel App

Ideally, we need a new laravel project where we will do our experiment; if you already have a project set up, jump onto subsequent step else execute the given command to download a new laravel app.

composer create-project --prefer-dist laravel/laravel laravel-hell-fire

Connect to MySQL Database

Database is the place where all the information is stored, add database name, username and password inside the .env to connect laravel to MySQL database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Add Algolia and Scout in Laravel

Let’s move on to the imperative instruction, recklessly install the Scout package through the Composer package manager in the Laravel app.

composer require laravel/scout

After adding Scout to Laravel, you must publish the Scout config file through the vendor publish command.

Above command prints the separate scoupt.php file in laravel’s app config directory.

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

Set the SCOUT_QUEUE variable to true inside the .env file.

SCOUT_QUEUE=true

Now, you have will have to add the Algolia PHP SDK via the Composer package manager in Laravel, make sure to execute the provided command:

composer require algolia/algoliasearch-client-php

Get and Add Algolia Keys in Laravel

To integrate and eloquently run text search in laravel, you have to have Algolia keys; this key allows the communication between laravel and algolia.

Head over to the Algolia site and obtain the key after signing up to their site.

Obtain Algolia Key

Right after getting the Algolia keys, again head over to the .env file, place the ALGOLIA_APP_ID and ALGOLIA_SECRET with their respective values or key.

ALGOLIA_APP_ID=algolia_application_id
ALGOLIA_SECRET=algolia_admin_api_key

Create Model & Migration

The php artisan command lets you create model and migration files altogether from command line tool.

php artisan make:model Student -m

Add the table value into the up() function, also you can add as many as values in the table. Update the database/migrations/create_students_table.php file.

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('student_name');
            $table->timestamps();
        });
    }

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

In the Model file, import Laravel Scout Searchable service, inject it into the model class, also pass the migration values in the fillable array, please update the app/Models/Student.php 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;
    use Searchable;

    public $fillable = ['student_name'];

    public function searchableAs()
    {
        return 'student_index';
    }    
}

The table structure has been created; push the table into the database using migrate command.

php artisan migrate

Generate + Set Up Controller

Next, use the command to manifest the controller in laravel; in this file, we will add the methods and functions to manage text search.

php artisan make:controller AlgoliaSearchController

Update Controllers\AlgoliaSearchController.php with following code.

<?php

namespace App\Http\Controllers;

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

class AlgoliaSearchController extends Controller
{
    public function index(Request $request)
    {
        if($request->has('find_student'))
        {
            $students = Student::search($request->find_student)
                ->paginate(8);
        }
        else
        {
            $students = Student::paginate(8);
        }
        return view('index', compact('students'));
    }

    public function search(Request $request)
    {
        $this->validate($request,['student_name'=>'required']);
        $students = Student::create($request->all());
        return back();
    }
}

Register New Routes

In the controller, we defined functions to get the records from the database, post the records to the database, use the controller to bind the methods to routes.

Please update routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AlgoliaSearchController;


Route::get('/students', [AlgoliaSearchController::class, 'index'])->name('students');
Route::post('/search-student', [AlgoliaSearchController::class, 'search'])->name('search.student');

Setting Up Laravel Blade View

Create index.php file in views folder, thereafter head over to resources/views/index.blade.php file and replace with the entire suggested code.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Laravel 8 Scout Algolia Text Search Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-4">
        <div class="col-md-12 mb-5">
            <form action="{{ route('search.student') }}" method="POST" autocomplete="off">
                @if(count($errors))
                <div class="alert alert-info">
                    <p><strong>Something went wrong</strong></p>
                    <ul>
                        @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
                @endif

                <input type="hidden" name="_token" value="{{ csrf_token() }}">

                <div class="form-group {{ $errors->has('student_name') ? 'has-error' : '' }}">
                    <input type="text" id="student_name" name="student_name" class="form-control" placeholder="Name"
                        value="{{ old('student_name') }}">
                    <span class="text-danger">{{ $errors->first('student_name') }}</span>
                </div>
                <div class="d-grid mt-3">
                    <button class="btn btn-dark">Add Student</button>
                </div>
            </form>
        </div>

        <div class="col-md-12">
            <form action="{{ route('students') }}" method="GET">
                <div class="form-group">
                    <input class="form-control" type="text" name="find_student"  placeholder="Search name"
                        value="{{ old('find_student') }}">
                </div>
                
                <div class="d-grid mt-3">
                    <button class="btn btn-outline-primary">Search Text</button>
                </div>
            </form>

            <table class="table text-center">
                <thead>
                    <th>Id</th>
                    <th>Name</th>
                </thead>
                <tbody>
                    @if($students->count())
                    @foreach($students as $key => $data)
                    <tr>
                        <td>{{ ++$key }}</td>
                        <td>{{ $data->student_name }}</td>
                    </tr>
                    @endforeach
                    @else
                    <tr>
                        <td colspan="4">No data found.</td>
                    </tr>
                    @endif
                </tbody>
            </table>
            {{ $students->links() }}
        </div>
    </div>
</body>

</html>

There are two components added to increase the laravel text search feature using the Bootstrap 5 CSS. You can add the student name through the simple form, add it into the table and search the table using the text query powered by Algolia scout.

View + Test App

The laravel text search module is almost ready; open the terminal, type command, and run the laravel app.

If developing locally, you may use the given url to view the app.

php artisan serve
http://127.0.0.1:8000/home

Laravel Scout Text Search

Conclusion

We have touched the tip of the iceberg; there are plenty of things you can add to Laravel Scout to make it more lethal; unquestionably, you may add more power to the full-text search widget of your laravel app.

More queries can be added to customize Laravel Text Searching, like you can paginate your search, soft delete model index, and even more play around with text search engine.

I hope you liked how we explained things in this tutorial; please share your feedback if you want to improve this guide.