D
D
dmytrotus2019-08-13 19:08:18
Laravel
dmytrotus, 2019-08-13 19:08:18

How to use merge with multiple tables in Laravel?

Project on Laravel.
There are 3 tables with goods.
I wanted to make a convenient search for all products.
After searching the internet, this is what I came up with.

use App\ProductTableOne;
use App\ProductTableTwo;
use App\ProductTableThree;

 public function search() {
    $search = request()->query('search');
    if ($search) {
        $ProductTableOne = ProductTableOne::where('title', 'LIKE', "%{$search}%")->get();  
        $ProductTableTwo = ProductTableTwo::where('title', 'LIKE', "%{$search}%")->get();  
        $ProductTableThree = ProductTableThree::where('title', 'LIKE', "%{$search}%")->get();  

        $TwoTables = $ProductTableOne->merge($ProductTableTwo); //сливаем 2 первых массива
        $products = $TwoTables ->merge($ProductTableThree); //доливаем 3ий массив к первым двум

    return view('myview')-with('products', $products);

So, it seems to me that the merge() function came out somehow, to put it mildly, not very elegant))) But rather a crutch. I tried to insert 2 arguments, it does not work, it takes only the first one.
Tell me how to fix the whole thing so that it is beautiful, and if there are 10 tables, so that one table does not need to be glued?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question