Merge multiple tables in Laravel / Lumen
Hello Friends, In this article I am going to show how to merge multiple tables in Laravel framework or Lumen micro framework. This is very useful for developers in many cases such as doing a search and showing search results from many tables. This method will work for both pure Laravel project and also with Lumen API project. So lets get start.
public function mergeTables(Request $request){
/*I defined a search text to find all matching data with following text from 3 tables*/
$searchText = 'Home';
/*I use like keyword to filter the data from all 3 tables. You can use your own*/
$searchByCategory = Category::where('name', 'like', '%' . $searchText . '%')->get();
$searchByPlace = Place::where('name', 'like', '%' . $searchText . '%')->get();
$searchByUser = User::where('name', 'like', '%' . $searchText . '%')->get();
/*Now we have to merge all tables into one array*/
$merge_outputs = array_merge(json_decode($searchByCategory, true),json_decode($searchByPlace, true),json_decode($searchByUser, true));
/*Finally we can output the results. Since I am using Laravel/Lumen as an API I have to output as below */
return response()->json($merge_outputs, 200);
/*Or If not you can pass the data to a view*/
// return view('home',compact('merge_outputs'));
}
Either you can return the results as a JSON in Lumen or you can pass the data to a view in Laravel.
Thats it!! now you can send axios requests. If you have any problems please comment below.
Or check my latest posts.