How to Create Full Text Search using Scout and Algolia Package?

Today now in this post i will show you How to Create Full Text Search using Scout and Algolia Package? Here I am going to give you an example with source code of How we can implement full text search in our laravel application by using scout and algolia package.

We know laravel is provide us the several feature and also introduce many packages. Laravel is also provide Scout Package for full text search from our Model. If we need to add the full text search function in our laravel application then i hope you can choose scout package for do this.

Now in this example i am going to explain this step by step. So you can easily understand and also use it in your laravel application. Now In this tutorial i will give you from scratch. So let’s start and follow the simple few step and implement the full text search function in your laravel application.

Step 1: Install Laravel Application

Now in the first step, if we don;t have laravel application setup then we need a fresh project. For get the fresh laravel application please run the bellow command and get a clean and fresh laravel application.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Packages

Now in this step we need to add two packages, so there are listed in bellow:

1)laravel/scout

2)algolia/algoliasearch-client-php

composer require laravel/scout

After the successfully install package, need to open config/app.php file and need to add service provider.

config/app.php

'providers' => [
	....
	Laravel\Scout\ScoutServiceProvider::class,
]
......

Now we need to publish the configure file by using the bellow command. After using this command run, we will find a new file scout.php in the config folder and we need to set configure details on it, so let’s run the bellow command:

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

Ok, now you need to install a package for “algolia”, so let’s run the bellow command:

composer require algolia/algoliasearch-client-php
Step 3: Package Configuration

Ok, now we need to set the id and the secret of algolia, so at first we need to create a new account in algolia.com. So if you haven’t any account on algolia.com site then click here and create a new account : algolia.com.

Ok, after the login we need to get a application id and also a secret. so click here and open on that web page: GET APP ID and SECRET. After open we will see the bellow screen and then copy your id and secret.

Ok, now nned to open our .env file and then need to paste id and secret as like as bellow:

.env

ALGOLIA_APP_ID=paste app id
ALGOLIA_SECRET=paste app secret
Step 4: Create Item Table and Model

Now need to create a model with table. For create the “items” table then we should create a Item model. So at first create the file in this path app/Model/Item.php and put the bellow content in item.php file:

php artisan make:model Item -m

app/Item.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Item extends Model
{
	use Searchable;
    public $fillable = ['title'];
    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function searchableAs()
    {
        return 'items_index';
    }
}

After this command we will find also one file in the following path database/migrations and we need to put the bellow code in our migration file for the create items table.

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


class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->timestamps();
       });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("items");
    }
}
Step 5: Add New Route

Now in this is step we need to create two new routes for one for add new items and one for listing. So now open your routes/web.php file and add the following route.

routes/web.php

Route::get('items-lists', ['as'=>'items-lists','uses'=>'ItemSearchController@index']);
Route::post('create-item', ['as'=>'create-item','uses'=>'ItemSearchController@create']);
Step 6: Create Controller

So now in this step, now we need to create a new controller as name ItemSearchController now in this path app/Http/Controllers/ItemSearchController.php. In this controller will manage all the listing of items and also add new the item request and it return response, So put the bellow content in controller file:

app/Http/Controllers/ItemSearchController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Http\Requests;
use App\Model\Item;


class ItemSearchController extends Controller
{


	/**
     * Get the index name for the model.
     *
     * @return string
    */
    public function index(Request $request)
    {
    	if($request->has('titlesearch')){
    		$items = Item::search($request->titlesearch)
    			->paginate(6);
    	}else{
    		$items = Item::paginate(6);
    	}
    	return view('item-search',compact('items'));
    }


    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function create(Request $request)
    {
    	$this->validate($request,['title'=>'required']);


    	$items = Item::create($request->all());
    	return back();
    }
}
Step 7: Create View

Now in the Last step , so let’s create the item-search.blade.php(resources/views/item-search.blade.php) for the layout and we will write the design code here and put the following code:

resources/views/item-search.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel - laravel scout algolia search example</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>


<div class="container">
	<h2>Laravel Full Text Search using Scout and algolia</h2><br/>


	<form method="POST" action="{{ route('create-item') }}" autocomplete="off">
		@if(count($errors))
			<div class="alert alert-danger">
				<strong>Whoops!</strong> There were some problems with your input.
				<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('title') ? 'has-error' : '' }}">
					<input type="text" id="title" name="title" class="form-control" placeholder="Enter Title" value="{{ old('title') }}">
					<span class="text-danger">{{ $errors->first('title') }}</span>
				</div>
			</div>
			<div class="col-md-6">
				<div class="form-group">
					<button class="btn btn-success">Create New Item</button>
				</div>
			</div>
		</div>
	</form>
	<div class="panel panel-primary">
	  <div class="panel-heading">Item management</div>
	  <div class="panel-body">
	    	<form method="GET" action="{{ route('items-lists') }}">


				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<input type="text" name="titlesearch" class="form-control" placeholder="Enter Title For Search" value="{{ old('titlesearch') }}">
						</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 table-bordered">
				<thead>
					<th>Id</th>
					<th>Title</th>
					<th>Creation Date</th>
					<th>Updated Date</th>
				</thead>
				<tbody>
					@if($items->count())
						@foreach($items as $key => $item)
							<tr>
								<td>{{ ++$key }}</td>
								<td>{{ $item->title }}</td>
								<td>{{ $item->created_at }}</td>
								<td>{{ $item->updated_at }}</td>
							</tr>
						@endforeach
					@else
						<tr>
							<td colspan="4">There are no data.</td>
						</tr>
					@endif
				</tbody>
			</table>
			{{ $items->links() }}
	  </div>
	</div>
</div>
</body>
</html>

Okay good, now we are ready for run this example so quick run by using the following command:

php artisan serve

Now need to open your browser and then run the bellow link:

http://localhost:8000/items-lists

If we have already the added few records on our table then we can index on that records by run the following command:

php artisan scout:import "App\Model\Item"

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →