Laravel 5 - Full Text Search Example using Scout and Algolia Packages
Today, I am going to give example source code of How to implement full text search in your laravel 5.3 application using scout and algolia.
Laravel 5.3 provide us several new feature and introduce new packages. Laravel 5.3 provide Scout Package for full text search from your Model. If you require to add full text search function in your laravel application then you have to choose scout package for to do.
In this example i going to explain step by step, so you can simple understand and use it in your laravel project. In this tutorial i give from scratch so let's follow simple few step and implement full text search function in your laravel application.
Preview:
Step 1: Install Laravel 5.3 Application
In this step, if you haven't laravel 5.3 application setup then we have to get fresh laravel 5.3 application. So run bellow command and get clean fresh laravel 5.3 application.
composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Packages
In this step we have to add two packages, there are listed bellow:
1)laravel/scout
2)algolia/algoliasearch-client-php
Ok, so first we will install "laravel/scout" package by following command:
composer require laravel/scout
After successfully install package, open config/app.php file and add service provider.
config/app.php
'providers' => [
....
Laravel\Scout\ScoutServiceProvider::class,
]
......
Now we have to publish configure file by using bellow command, After this command run, you will find new file scout.php in config folder and we will set configure details on it, so let's run bellow command:
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Ok, now we have to install package for "algolia", so let's run bellow command:
composer require algolia/algoliasearch-client-php
Step 3: Package Configuration
Ok, now we have to set id and secret of algolia, so first you have to create new account in algolia.com. So if you haven't account on algolia.com site then click here and create new account : algolia.com.
Ok, after login we have to get application id and secret so click here and open that web page: GET APP ID and SECRET. After open you will see bellow screen and copy your id and secret.
Ok, now open your .env file and paste id and secret like as bellow:
.env
ALGOLIA_APP_ID=paste app id
ALGOLIA_SECRET=paste app secret
Step 4: Create Item Table and Model
In this step we have to create migration for items table using Laravel 5.3 php artisan command, so first fire bellow command:
php artisan make:migration create_items_table
After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for 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");
}
}
After create "items" table you should create Item model for items, so first create file in this path app/Item.php and put bellow content in item.php file:
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';
}
}
Step 5: Add New Route
In this is step we need to create routes for add new items and listing. so open your routes/web.php file and add 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
In this step, now we should create new controller as ItemSearchController in this path app/Http/Controllers/ItemSearchController.php. this controller will manage all listing items and add new item request and return response, so put 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\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
In Last step, let's create item-search.blade.php(resources/views/item-search.blade.php) for layout and we will write design code here and put following code:
resources/views/item-search.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.3 - 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>
Ok, now we are ready to run this example so quick run by following command:
php artisan serve
Now open your browser and run bellow link:
http://localhost:8000/items-lists
If you have already added few records on your table then you can index that records by run following command:
php artisan scout:import "App\Item"
Ok, so you can check on your and you can get more information about laravel scout form here : Click Here.
Maybe it can help you.....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.