John Davidson

php - how to use multiple filter in laravel


I want to filter data from multiple tables so I write query like that and one thing I let you know that both data1 and data2 return same column with different data.

$data1 = collect(DB::table('table_1')->get()->toArray());
$data2 = collect(DB::table('table_2')->get()->toArray());
$results = $data1->merge($data2);
if ($request->name!="") {
$results->when(request('name'), function($q){
$q->Where('name', request('name'));
return $results;

But $results returns all data and not filter data

My Answer:

$data2 = collect(DB::table('table_2')->select('column_name')->where('condition')->get();

$filteredData = $data1->merge($data2);

This code snippet uses the Laravel Query Builder to retrieve data from two different tables and filter them based on a condition. The collect() method is used to convert the query results into a collection, which allows for easy manipulation of the data. The merge() method is then used to combine the data from both tables into a single collection.

You can further refine the filtering by adding additional where clauses or conditions to the query.

Rate this post

3 of 5 based on 2234 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us