Laravel 5 full text search box with example

By | June 7, 2018
Laravel 5 full text search box with example

Hi guys, We generally need a search box in almost each dynamic website and when we do work on reports module for any type of web application. It is must to implement search feature. So here i am going to tell you  laravel 5 full text search box with example. Laravel has various packages to provide search feature but here we will implement “nicolaslopezj/searchable” package.

There are some steps to integrate this package in our application so lets start by installing. So follow these steps.

Step 1: Package Installation

In the first step execute the below command in your terminal or command prompt.

composer require nicolaslopezj/searchable

After executing above command all the required files will be downloaded in your application.

Step 2: Package Setup

In the second step, we will setup installed package in our application. We will implement search feature in laravel default User model. So add SearchableTrait in user model like the code below

app/User.php

<?php


namespace App;


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


class User extends Authenticatable
{
    use Notifiable;
    use SearchableTrait;


     /**
     * Searchable rules.
     *
     * @var array
     */
    protected $searchable = [
        'columns' => [
            'users.name' => 10,
            'users.email' => 5,
            'users.id' => 3,
        ]
    ];


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];


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

Step 3: Add a Route

In this step we will add a route in routes/web.php file. So open that file and just copy and paste the below code.

Route::get("my-search","HomeController@userSearch");

Step4: Create a Controller

You can create a new controller to handle and process the request and your logic but here i am using Laravel’s default controller that is HomeController. And we will add userSearch() in HomeController file. So open that file and include userSearch() method.

app/Http/Controllers/HomeController.php

<?php


namespace App\Http\Controllers;


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


class HomeController extends Controller
{


    public function mySearch(Request $request)
    {
    	if($request->has('search')){
    		$users = User::search($request->get('search'))->get();	
    	}else{
    		$users = User::get();
    	}


    	return view('my-search', compact('users'));
    }


}

Step 5: Create a View File

In this step we will create a view file to display the search results. So create user-search.blade.php file and copy the below code in that file.

resources/views/my-search.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.5 Full Text Search Example</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
</head>


<body>
  <div class="container">
    <h1>Laravel 5.5 Full Text Search Example</h1>


    <form method="GET" action="{{ url('my-search') }}">
      <div class="row">
        <div class="col-md-6">
          <input type="text" name="search" class="form-control" placeholder="Search" value="{{ old('search') }}">
        </div>
        <div class="col-md-6">
          <button class="btn btn-success">Search</button>
        </div>
      </div>
    </form>


    <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">Result not found.</td>
      </tr>
      @endif
    </table>


  </div>
</body>
</html>