Laravel Search Query Example with Like Operator

Throughout Laravel Search Query Example with Like Operator; you will learn how to use like query to get matched pattern in laravel application. The LIKE query is used in a WHERE clause to search for a specified pattern in a column. For using like query we need to put % and _ wildcard with our query for getting matched results.

The laravel like query filter the result according the search params. You can use this exmaple in laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 apps as well;

Example 1: Get Same Like Field

Search query with where and like operator;

public function users(Request $request)
{
    $search = "john"; //$request->name;
    
    $users = User::where('name',  'LIKE',  '%'.$search.'%')
        ->get();

    dd($users);
}

Example 2: Multiple like query

Search query with where, orWhere and like operator;

public function index(Request $request)
{
	$name = 'john';  // $request->name;
	$email = 'john@example.com';  // $request->email

	$users = User::where('name', 'LIKE', '%'.$name.'%')
		->orWhere('email', 'LIKE', '%'.$email.'%')
		->get();

         dd($users);
}

Example 3: Custom search builder

You may want to build custom Scout search builder method. To create macro Builder, first add below method into boot() method of App\Providers\AppServiceProvider or any service provider.

use Illuminate\Database\Eloquent\Builder;

Builder::macro('whereLike', function(string $column, string $search) {
   return $this->orWhere($column, 'LIKE', '%'.$search.'%');
});

Now you can use whereLike() method into controller.

public function index(Request $request)
{
	$name = 'john';  // $request->name;
	$email = 'john@example.com';  // $request->email

	$users = User::where('name', 'LIKE', '%'.$name.'%')
		->orWhere('email', 'LIKE', '%'.$email.'%')
		->get();

         dd($users);
}

This will return all records which matched pattern from name or email columns.

I hope you enjoy search result using like query in laravel.

Leave a Comment