Laravel Scout Algolia Search: The Complete Guide

2
265
Laravel Scout Search Tutorial With Example

In this example, we use the scout package that provides full-text search functionality. First, let’s Configure Laravel Project.

Laravel Scout Algolia Search

Laravel Scout is search engine-agnostic; it keeps things basic. For indexing, this isn’t an issue, as Scout will help keep everything in sync and format your data the way you want. But for search, it’s limited. If you need to get more information, then go to Laravel.

Step 1: Download Laravel Project

Establish a Laravel Project by typing the following command.

composer create-project --prefer-dist laravel/laravel scout

Step 2: Setup SQL Database

Now we can set up database credentials.

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

Step 3: Install Scout Package

First, install Scout via the Composer package manager.

composer require laravel/scout

After installing Scout, you should publish the Scout configuration using the vendor: publish Artisan command.

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

Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application’s web interface.

Set the value of the queue in the .env file.

SCOUT_QUEUE = true

Step 4: Install the Algolia Driver.

You will also want to install the Algolia PHP SDK via the Composer package manager,

composer require algolia/algoliasearch-client-php

Next, we have to set the id and secret of Algolia. So move to this website Algolia and then create your account.

After login, You can get your id and secret from this link: https://www.algolia.com/api-keys.

laravel scout algolia tutorial

You can set id and secret in your .env file.

ALGOLIA_APP_ID = Enter your Application ID
ALGOLIA_SECRET = Enter your Admin API Key

Step 5: Register Trait in Model 

Finally, add the Laravel\Scout\Searchable trait to the model you would like to make searchable. To modify the model file.

//User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;


class User extends Model
{
    use Notifiable;
    use Searchable;


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];
    public function searchableAs()
    {
        return 'users_index';
    }

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Step 6: Batch Import

In this example, we have no records, So first, we will create a dummy record by typing the following command.

php artisan tinker

factory(App\User::class, 100)->create();

Database records need to import into your search driver. Scout provides an Artisan command that you may use to import all of your existing records into your search indexes.

php artisan scout:import "App\User"

Step 7: Create a View File

Create a file in resources  >>  views  >>   index.blade.php and put the following code in it.

//index.blade.php

<!DOCTYPE html>
<html>
<head>
    
    <meta charset="utf-8">
    <title>Laravel Scout Search Tutorial</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
    </head>

   <body>
    <div class="container">
        <h1>Laravel Scout Search Tutorial</h1>
      <form method="GET" action="{{ url('index') }}">
            <div class="row">
                <div class="col-md-6">
                    <input type="text" name="search" class="form-control" placeholder="Search">
                </div>
                <div class="col-md-6">
                    <button class="btn btn-info">Search</button>
                </div>
            </div>
        </form>
   <br/>
      <table class="table table-bordered">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
            @if(count($users) > 0)
                @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
                @endforeach
            @else
            <tr>
                <td colspan="3" class="text-danger">Result not found.</td>
            </tr>
            @endif
        </table>
   </div>
</body>
</html>

Step 8: Create a Controller and route

 php artisan make:controller SearchController

It will build a controller file called SearchController.php.

Add the following code into the controller.

<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function search(Request $request)
    {
    	if($request->has('search')){
    		$users = User::search($request->get('search'))->get();	
    	}else{
    		$users = User::get();
    	}
        return view('index', compact('users'));
    }
}

We register the route in a web.php file.

Route::get('index','SearchController@search');

laravel scout tutorial

If you search like Vince, then you can see the result like the below image.

That’s it for this guide. Thanks for taking it.

2 Comments

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.