Search In Laravel 5

Last Updated at : July 18, 2017 By - Azeem Hassni | 2214

    Introduction

    Search is the most tricky part in every application while everyone wants a quick and effective search engine for their application. Let’s see how we can make this process easy and scalable in a Laravel application. We will use a package called TNTSearch which is a full-text search engine written in PHP.

    Installing TNT Search

    Since we’ve composer as industry standard so installing packages is not a problem. just add the following line in your composer.json file

    {
      "require" : {
          "teamtnt/tntsearch": "0.6.*"
       }
    }
    

    or simply run the following command right from your terminal.

    $ composer require teamtnt/tntsearch
    

    it will pick appropriate version for you.

    Now open up config/app.php and register the following service provider and create an alias for the namespaced facade.

    Service Provider

    TeamTNT\TNTSearch\TNTSearchServiceProvider::class,
    

    Alias

    'TNTSearch' => TeamTNT\TNTSearch\Facades\TNTSearch::class,
    

    Now that the installation part is done, let’s dive into the cool stuff.

    Indexing

    Let’s say we’ve a products table with Title, Description and Price fields, we will create an artisan command to perform our indexing operations.

    Open a terminal window and execute the following command to generate ProductIndexer class.

    $ php artisan make:console ProductIndexer
    

    Locate the file at app/Console/Commands/ProductIndexer.php and set handle method like this

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use TeamTNT\TNTSearch\Facades\TNTSearch;
    
    class ProductIndexer extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'index:products';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Index the Products';
    
        /**
         * Create a new command instance.
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $indexer = TNTSearch::createIndex('products.index');
            $indexer->query("SELECT id, title, description, price FROM products");
            $indexer->run();
        }
    }
    

    Cool! Now Register the command with Laravel by appending the following line into the $commands array in app/Console/Kernal.php

    \App\Console\Commands\ProductIndexer::class
    

    Our indexing part is almost done, we can index our products any time by running the following artisan command

    $ php artisan index:products
    

    You can find the newly generated index file atstorage/products.index

    Performing a Search

    Let’s setup a search form real quick with routes and controller actions

    # Displays our search form
    Route::get('products', 'ProductsController@index');
    
    
    
    # Displays our search results
    Route::get('products/search', 'ProductsController@search');
    

    From PrdouctController@index we’ll simply return a view which renders our search form and we’ll submit that form to ProductsController@search

    Let’s see how to tackle the search part,

    <?php 
    
    namespace App\Http\Controllers;
    
    use App\Http\Requests;
    use App\Product;
    use Illuminate\Http\Request;
    use TeamTNT\TNTSearch\Facades\TNTSearch;
    
    class ProductsController extends Controller
    {
        ....
    
        public function search( Request $request )
        {
            TNTSearch::selectIndex("products.index");
            
            $results = TNTSearch::search($request->get('query'), 1000);
    
            $products = Product::whereIn('id', $results[ 'ids' ])->get();
    
            return view('search.results', compact('products'));
        }
        
        ....
    }
    

    We’re almost done, now our site has a basic but powerful search engine.

    List of all products

    Search Results

    I’ll share an other part of this article to discuss re-indexing and moving the indexing jargon to background using Laravel’s scheduler.

    Thanks,

    Follow me on Twitter || Read this on Medium

    blog user
    Azeem Hassni

    I write code and i love it. I do write blogs on things which I am passionate about. I love to Explore the internet of things and whats new in web technologies. My topic of Interests include WordPress, Laravel & Magento to name a few.

    Related Posts

    Getting an app developed is not the only thing that one needs to ensure in terms of digital visibility and e-commerce. Yes, having an app is important but to stay updated and to be abreast with the competition Optimization of performance is necessary.

    Telescope gives knowledge into the solicitations coming into your application, exemptions, log sections, database questions, lined employments, mail, notices, reserve activities, planned errands, variable dumps and that's just the beginning.

    Laravel Live Islamabad, ended on 24th Nov'18 & we got a lot to learn from the top-notch of speakers & influencers. Thanks to the sponsors for pulling off such a great event in the capital of Pakistan.

    Previously Localization in Laravel was done by creating separate directories for each locales and place in under resources/lang/ and add key value pairs to every single keyword in a number of files as per their modules.