Site Admin
Site Admin Founder of MeaningArticles
479 Views

Laravel Scout Algolia Search: The Complete Guide example

Hello Dev.

Laravel Scout is search engine-agnostic, it continues things fundamental. For indexing, this isn’t an difficulty, as Scout will assist maintain everything in sync and format your data the manner you need. however for search, it’s restrained. in case you want to get more information, then visit https://laravel.com/docs/master/scout.

Laravel Scout Algolia Search

In this example, we use the scout package that provides complete-text search capability. permit’s Configure Laravel Project.

So let's start the lesson...

 

Step 1: Install Laravel 8

First of all we want to get clean and new Laravel application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it:

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

 

Step 2: Configuration of Database

Second step, we configure database like database name, username, password etc application of laravel. let's open .env file and fill complete details equal as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(scout)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

 

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 the use of the vendor: publish Artisan command.

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

Running a queue worker will permit Scout to queue all operations that sync your model information to your search indexes, imparting a great response times for your application’s web interface.

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

SCOUT_QUEUE = true

 

Step 4: Install the Algolia Driver

you will additionally want to put in the Algolia PHP SDK thru 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 https://www.algolia.com/ and then create your account.

After login, you could get id and secret from this hyperlink: https://www.algolia.com/api-keys

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

Sooner or later, add the Laravel\Scout\Searchable trait to the model you would love to make searchable. To adjust 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 haven't any records So first we can create a dummy record with the aid of typing the subsequent command.

php artisan tinker

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

Database records need to import into your search driver. Scout offers an Artisan command that you could use to import all your current 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 placed this following code in it.

index.blade.php

<!DOCTYPE html>
<html>
<head>
    
    <meta charset="utf-8">
    <title>Laravel Scout Algolia Search example - meaningarticles.com</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 Algolia Search example - meaningarticles.com</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's going to build a controller file known as SearchController.php.

Add the following code into the controller.

SearchController.php

<?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 route in a web.php file.

Route::get('index','[email protected]');

Finally, Our Laravel Scout Algolia search example is over.

I hope it assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.

Happy Coding.....