A full-text search feature in a web application is incredibly useful for users to navigate through content-rich web and mobile applications, as demonstrated in this Laravel Scout full text search tutorial.
This thorough guide will show you how to use the Laravel Scout algolia module to deeply integrate full-text search into a Laravel application.
To create a full-text search using Laravel Scout Algolia, we will gradually lift the veil on each step that must be shared;
Because of Laravel Scout, adding or using Algolia in Laravel has become really simple. The robust scout package provided by Laravel Scout enhances the integration of full-text search right into your model.
A straightforward driver-based solution for adding full-text search functionality to your Eloquent models is provided by Laravel Scout. Scout automatically keeps your search indexes in sync with your Eloquent records by using model observers.
Although Scout already provides drivers for Algolia and MeiliSearch, building custom drivers has never been simple, even though you are free to freely extend Scout with your own own search implementations.
Laravel 9 Algolia Full Text Search Example
- Create New Laravel Project
- Update Database Details in ENV
- Install Laravel Scout & Algolia Packages
- Set Up Algolia in Laravel
- Set Up Model and Migration
- Set Up Controller
- Create Routes
- Configure Blade View
- Run Laravel Project
Create New Laravel Project
First, enter the console, type the following command, and then correctly execute the command to install the new Laravel app. If the app has already been created, ignore the following command.
composer create-project --prefer-dist laravel/laravel laravel-demo
Enter the app’s folder after it has been created:
cd laravel-demo
Update Database Details in ENV
The database name, username, and password must then be entered in the .env configuration file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Install Laravel Scout & Algolia Packages
Using the composer tool, we must now install the laravel scout and algolia search dependencies; these packages are necessary to create instant search functionality in laravel.
Let’s use the laravel scout package installation command.
composer require laravel/scout
The Scout configuration file should be published using the vendor: We have introduced the Scout library to Laravel; let’s let Laravel know that it exists as well. publish the artisan order.
The scout.php configuration file will be published to the config directory of your application when the following command is executed:
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Next, make the following change to the .env file’s line of code.
SCOUT_QUEUE=true
Execute the following command to add the Laravel package for the Algolia search client.
composer require algolia/algoliasearch-client-php
Set Up Algolia in Laravel
In order to obtain the API keys in this section, we must visit the Algolia website and register.
Algolia not only provides excellent UX for the web and e-commerce apps, but also AI-powered search & discovery across websites & apps.
You must go to the API Keys area and then search for the Your API Keys part on the API Keys page. In the .env configuration file, define the Application ID and Admin API keys after copying them from there.
ALGOLIA_APP_ID=add_application_id
ALGOLIA_SECRET=add_admin_api_key
Set Up Model and Migration
In order to add a new table to the database, this step demonstrates how to construct a Model by similarly setting up the model and running a migration. Let’s use the command below to create the new Product model file.
php artisan make:model Product -m
Next, you must update the values in the Product table in the app/Models/Product.php file, which will be added to the database. Ideally, we also need to define the searchableAs() method and import the Scout Searchable service.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Product extends Model
{
use HasFactory;
use Searchable;
public $fillable = ['product_name'];
/**
* Get the index name for the model.
*/
public function searchableAs()
{
return 'product_index';
}
}
The next step is to add the following code to the database/migrations/create products table.php file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
To begin the migration, issue the following command.
php artisan migrate
Set Up Controller
You are instructed to construct a new controller in this phase of the tutorial, where we will put the code to display the search component in view and develop the full-text search feature.
php artisan make:controller TextSearchController
Once the new controller has been created, add the following code to TextSearchController.php in the app/Http/Controllers directory.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Product;
class TextSearchController extends Controller
{
public function index(Request $request)
{
if($request->has('product_search')){
$products = Product::search($request->product_search)
->paginate(7);
}else{
$products = Product::paginate(7);
}
return view('welcome', compact('products'));
}
public function fullTextSearch(Request $request)
{
$this->validate($request,['product_name'=>'required']);
$products = Product::create($request->all());
return back();
}
}
Create Routes
We must open the routes/web.php file in this section and define the two routes that Laravel will use to handle text search simultaneously.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TextSearchController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/products', [TextSearchController::class, 'index'])->name('products');
Route::post('/create-product', [TextSearchController::class, 'fullTextSearch'])->name('createProduct');
Configure Blade View
The blade view needs to be created for the final stage of this in-depth tutorial, so open the default welcome.blade.php file and add the following code.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Algolia Scout Full 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-5" style="max-width: 800px">
<form method="POST" action="{{ route('createProduct') }}" autocomplete="off">
@if(count($errors))
<div class="alert alert-danger">
<strong>Whoops!</strong> Error occured
<br />
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-md-6">
<div class="form-group {{ $errors->has('product_name') ? 'has-error' : '' }}">
<input type="text" id="product_name" name="product_name" class="form-control"
placeholder="Enter Name" value="{{ old('product_name') }}">
<span class="text-danger">{{ $errors->first('product_name') }}</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<button class="btn btn-outline-danger">Add Product</button>
</div>
</div>
</div>
</form>
<div class="panel panel-primary mt-4">
<div class="panel-heading mb-2"><strong>Maange products:</strong></div>
<div class="panel-body">
<form method="GET" action="{{ route('products') }}">
<div class="row mb-5">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="product_search" class="form-control"
placeholder="Search by name" value="{{ old('product_search') }}">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<button class="btn btn-success">Search</button>
</div>
</div>
</div>
</form>
<table class="table text-center">
<thead>
<th>#Id</th>
<th>Name</th>
<th>Create Date</th>
<th>Updated Date</th>
</thead>
<tbody>
@if($products->count())
@foreach($products as $key => $product)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $product->product_name }}</td>
<td>{{ $product->created_at }}</td>
<td>{{ $product->updated_at }}</td>
</tr>
@endforeach
@else
<tr>
<td colspan="4">There are no data.</td>
</tr>
@endif
</tbody>
</table>
{{ $products->links() }}
</div>
</div>
</div>
</body>
</html>
Run Laravel Project
Let’s run the command to launch the application to call the Laravel development server.
php artisan serve
To view the app, enter the URL listed below.
http://127.0.0.1:8000/products
Conclusion
We have just finished the Laravel Algolia full-text search lesson; throughout it, we saw how full-text search works and is integrated.
However, Laravel Scout has a tons of additional capabilities that might enhance your search and make it more user-friendly. We hope that this step-by-step explanation will clarify the idea of full-text search for you.