Laravel where LIKE query example tutorial

When you put the search form in your application, you need to use like query to get matched pattern. TThe LIKE query is used in a WHERE clause to search for a specified pattern in a column. You can use SQL % and _ wildcard into Laravel to get matched results.

Let's look the example, Your application have filter result by countries list. The user may have searched for "United States" instead of "United States of America". So in this cases you need to also filter result for country "United States of America".

Example 1:

/**
* filter the user result
*
* @var array
*/
public function users()
{
    $search = "United States";
    
    $users = User::where('country', 'LIKE', '%'.$search.'%')
        ->get();

    dd($users);
}

This will create below SQL query:

SELECT * FROM `users` WHERE `country` LIKE '%United States%';

This will also include users cuntries with United States of America.

Example 2: Multiple like query

Now you may want to search into multiple columns. For that, you may use orWhere() method.

/**
* filter the user result
*
* @var array
*/
public function index()
{
	$search = 'john';
	
	$users = User::where('name', 'LIKE', '%'.$search.'%')
		->orWhere('email', 'LIKE', '%'.$search.'%')
		->get();
}

Example 3: Custom search builder method

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.

/**
* filter the user result
*
* @var array
*/
public function index()
{
	$search = 'john';

	$users = User::whereLike('name', $search)
		->whereLike('email', $search)
		->get();
}

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

So this way, you can improve search result using like query.