Laravel Search Query Example with Like Operator

In this Laravel tutorial, I will discuss the topic of the Laravel 8 search query and I will use like operator to search from s specific model in Laravel. So basically from this Laravel like query tutorial, you will learn how to use Laravel 8 like query to search a model data with the search key.

In my many previous tutorials, I showed how to search a model by key in Laravel. But in this example, I will simply show you a demo search application. We will pass a search key and we will search from the Post model using the like operator in Laravel.

There are so many ways to search data in Laravel applications like laravel scout or algolia etc. But in this example, we will see a very simple search example in Laravel using like query.

 

Step 1: Download Laravel

Before starting this Laravel search query like tutorial, we need a fresh Laravel application. So run below command to get it.

laravel new search

 

Read also: Laravel Search Multiple Models using Spatie Searchable Package

 

Step 2: Create Route

In this step, we have to create a route to make a Laravel search query example tutorial. 

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;

Route::get('/search/', [SearchController::class,'search'])->name('search');

 

Step 3: Create controller

Now in this step, we need a controller to write this search query to get search data in Laravel. So create it like below:

App\Http\Controllers\SearchController.php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function search(Request $request){
       
        $search = $request->input('search');
  
        $posts = Post::query()
                    ->where('title', 'LIKE', "%{$search}%")
                    ->orWhere('body', 'LIKE', "%{$search}%")
                    ->get();
        
        return view('search', compact('posts'));
    }
}

 

Let assume we had two attributes like title and body in our posts table.

 

Read also: Use When() Condition in Eloquent Filter Query in Laravel

 

Step 4: Create Blade File

Now that we have the route and the controller all that is set to go, we just need to create a form in our search.blade.php file.

resources/views/search.blade.php

 

Then to display the results that file like below:

resources/views/search.blade.php

 

Recommended: Advanced Search Filter using Dropdown in Laravel

 

Okay, all are set to go. You can test now to search your model that it is working or not. 

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js