Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aspiresuvedi's avatar

Search all the columns using laravel query builder

This is much of a sql related question. But I need to solve it in a laravel way. I have to implement a search functionality which makes search on every column of the table and join table. I have used postgres as database and query needs to be perfomed in json column type also.

My query looks like this

$cases = \DB::table('cases')
            ->join('services', 'cases.id', '=', 'services.case_id')
            ->where(function($query) use ($request)
            {
                $query->whereRaw('*', 'like', '%'.$request->get('query').'%');
            })
            ->get();

I need to perfom where query to all columns.

0 likes
4 replies
pmall's avatar
$columns = [...];

$query = YourModel::select('*');

foreach($columns as $column)
{
  $query->where($column, '=', $search_value);
}

$models = $query->get();
6 likes
togo_hgl's avatar

Works like a charm, although i would like to recommend

$query = YourModel::all();

also when pushing the results you'd probably want to use php array_push method and use an array for the responses:

$query = YourModel::all(); // Get all data of the class

$search_value = 'teststring'; // searchstring
$columns = array('test', 'test2'); // could also be used like $columns = ['test', 'test2'];

$resultsarray = array();

	foreach ($columns as $column) {
    	$results = $query->where($column, $search_value);
        if ($results != '[]') {
        	array_push($resultsarray, $results);
        }
	}

$result = $resultsarray;

I hope this may help some people in the future for reference :)

Please or to participate in this conversation.