Searching Model data using laravel spatie searchable.

serachable

In this tutorial, I’ll explain how to use Spatie Searchable package to search model data in Laravel.

Laravel searchable package gives us to get easy structured to find the data into a model that helps to implement it in different resources.

Searching View:



Overview Of Task:

  • Step 1: Install the laravel-searchable package.
  • Step 2: Create a Model & Database updation.
  • Step 3: Using Model and Controller to searchable.
  • Step 4: Create a route.
  • Step 5: Create Blade Files.

Step 1: Install the laravel-searchable package.

First of all, we need to get spatie laravel-searchable using bellow command, So open your terminal OR command prompt and run bellow command:

composer require spatie/laravel-searchable

Step 2: Create a Model & Database Schema.

In the second step, we have to create a model and database schema. Create a model with database migration.

php artisan make:model Post -m
Schema::create('post', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });

Step 3: Using Model and Controller to searchable.

You need to implement our Model Post.php searchable, so open your model app/Post.php and put the below code.

<?php

namespace App;

use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Illuminate\Database\Eloquent\Model;

class Post extends Model{
    public $table = 'post';
    protected $guarded = [];
    protected $fillable = [
        'title', 'body'
    ];
    public function getSearchResultofPost(): SearchResult{
        $url_post = route('viewpost', $this->id);
	        return new SearchResult(
	            $this,
	            $this->title,
	            $url_post
	        );
    }
}

Now I’ll explain to you how it codes works exactly, so you can see we already implement our Model for the searchable and our method is getSearchResultofPost.

getSearchResultofPost method needs to return class SearchResult, and which in turn requires three parameters.
1. $this denotes the current Model class.
2. $this->title denotes we will return person name as part of the search result
3. Here we are linking to the show URL which shows the single person name.

Now you have to open your Controller file app/Http/Controllers/PostController.php and put the below code.

<?php

namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Spatie\Searchable\Search;

class PostController extends Controller{
     public function index(){
        return view('search');
    }
    public function search(Request $request){
        $searchResultsPost = (new Search())
            ->registerModel(Post::class, 'title')
            ->perform($request->input('query'));
        return view('search', compact('searchResultsPost'));
    }
}

Step 4: Create a route.

Route::post('search', 'PostController@search')->name('search');
Route::get('search', 'PostController@index')->name('search');

Step 5: Create Blade Files.

In this step, we have to find resources/views and create a new folder name search & put the below code.

First, you have had to create search.blade.php


@extends('layouts.app')
@section('content')
  <div class="postserach">
      <div class="text-center"><b>{{ $searchResultsPost->count() }} results found for "{{ request('query') }}"</b></div>

      <div class="text-fiord-blue text-center">
          @foreach($searchResultsPost->groupByType() as $type => $modelSearchResults)
              <h2>{{ ucfirst($type) }}</h2>
          @endforeach
      </div>
  </div>
  <section class="featured-posts no-padding-top">
    <div class="container">
      <!-- Post-->
      @foreach($searchResultsPost as $modelSearchResults)
        <div class="row d-flex align-items-stretch">
          <div class="text col-lg-7">
            <div class="text-inner d-flex align-items-center">
              <div class="content">
                <header class="post-header">
                  <div class="category"><a href="#">Business</a><a href="#">Technology</a></div><a href="post.html">
                    <a href="{{ $modelSearchResults->url }}" class="text-fiord-blue">
                      <h2 class="h4">{{ $modelSearchResults->title }}</h2>                           
                    </a>
                </header>
                <p>
                  {!!  str_limit($modelSearchResults->searchable->body, 120) !!}
                  <a href="{{ $modelSearchResults->url }}" class="btn btn-group-justified" style="padding: unset !important;">
                      Read more  
                      <i class="fa fa-arrow-right"></i>
                  </a>
                </p>
                <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap">
                    <div class="avatar"><img src="images/avatar-1.jpg" alt="..." class="img-fluid"></div>
                    <div class="title"><span>{{ $modelSearchResults->searchable->name }}</span></div></a>
                  <div class="date"><i class="icon-clock"></i>{{ $modelSearchResults->searchable->created_at }}</div>
                  <div class="comments"><i class="icon-comment"></i>12</div>
                </footer>
              </div>
            </div>
          </div>
          <div class="image col-lg-5">
            <img src="{{ route('blog_image_display', $modelSearchResults->searchable->files) }}" alt=""/>
          </div>
        </div>
        <br>
      @endforeach
    </div>
  </section>
@endsection

Now we are ready to run our task with laravel, so run bellow command for the run:

php artisan serve

Now you have to open your browser and put below URL:

http://localhost:8000/search/

Notice:

You have to create A Post on this tutorial with help my previous tutorial Laravel CRUD Operation for a beginner.
It will help to How to create a Post with CRUD Operation.

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!