Laravel Full Text Search Tutorial With Example

Hello coders, In this tutorial, I will show you how to do Laravel Full Text Search Tutorial. In this example, we use nicolaslopezj/searchable Package for full-text search. We will use full-text search to find users by matching any of the columns name, email. For more information, you can follow this link.

Laravel Full Text Search Tutorial

We are going to Configure Laravel Project.

#1: Download Laravel Project

Install New Laravel Project by the writing following command.

$ composer create-project --prefer-dist laravel/fulltextsearch

#2: Configure SQL Database

Now we can setup database credentials.

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

#3: Install searchable Package

Now we will install nicolaslopezj/searchable Package in our project.

 composer require nicolaslopezj/searchable

#4: Migrate Table

Next, Migrate table by typing following command in cmd.

php artisan migrate

It will create two tables.

  1. create__users_table
  2. create__passoword_resets_table

Laravel provides a fast way to scaffold all of the routes and views you need for authentication using one simple command:

php artisan make:auth

This command should be used on new applications and will install a layout view, registration and login views, as well as routes for all authentication end-points.

#5: Modify Model

Laravel by default provide the User.php model. In this example, you can change model file because we add traits and search rules in User.php file.

//User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Nicolaslopezj\Searchable\SearchableTrait;

class User extends \Eloquent
{
    use Notifiable;
    use SearchableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $searchable = [
        'columns' => [
            'users.name' => 10,
            'users.email' => 5,
        ]
    ];
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

In this tutorial, we can register the user in a database then fetch the user from them. OR  you can create dummy data by typing following command.

php artisan tinker

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

#6: Create a view file

Create a file in resources  >>  views  >>   search.blade.php and put this following code in it.

//search.blade.php

<!DOCTYPE html>
<html>
<head>
    
    <meta charset="utf-8">
    <title>Laravel Full Text 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 Full Text 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-primary">Search</button>
				</div>
			</div>
		</form>
   <br/>
      <table class="table table-bordered">
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Email</th>
			</tr>
			@if($users->count())
				@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>

#7: Create one controller

 php artisan make:controller SearchController

It will create a controller file called SearchController.php.

Add code to search() function to display view.

//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('search', compact('users'));
    }    
}

#8: Define Route

We register route in a web.php file.

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

Implementing Full Text search in Laravel

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

Full Text Search in Laravel 5

If you search like ab, then you can see that Result Not Found because there is no such record like ab.

Laravel Full Text Search Example

Possible Error : SQLSTATE[42000]: Syntax error or access violation: 1055 ‘fulltextsearch.users.name’ isn’t in GROUP BY (SQL: select * from (select `users`.*, max((case when LOWER(`users`.`name`) LIKE tr then 150 else 0 end) + (case when LOWER(`users`.`name`) LIKE tr% then 50 else 0 end) + (case when LOWER(`users`.`name`) LIKE %tr% then 10 else 0 end) + (case when LOWER(`users`.`email`) LIKE tr then 75 else 0 end) + (case when LOWER(`users`.`email`) LIKE tr% then 25 else 0 end) + (case when LOWER(`users`.`email`) LIKE %tr% then 5 else 0 end)) as relevance from `users` group by `users`.`id` having relevance >= 3.75 order by `relevance` desc) as `users`)

Possible Solution :  Edit your applications’s database config file config/database.php

In mysql array, set strict => false to disable MySQL’s strict mode.

At last, our Laravel Full Text Search Tutorial is over.

Post Your Thoughts

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