Home > Software engineering >  How to merge all models in laravel 9?
How to merge all models in laravel 9?

Time:06-17

I want to show all slideshow when the images are not blank.

public function index()
{

    $sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
    $sliderServices = Service::query()->select('slider')->whereNotNull('slider');
    $slideShows = $sliderProducts->merge($sliderServices)
        ->union($sliderProducts)
        ->union($sliderServices)
        ->get();
    return view('Home.index', compact('slideShows'));
}

CodePudding user response:

$sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
$sliderServices = Service::query()->select('slider')->whereNotNull('slider');

$sliderProducts and $sliderServices will both be instances of Illuminate\Database\Eloquent\Builder class

You need to fetch the collection before trying to merge them

To get the collection you can use get() on the Builder. Try

public function index()
{

    $sliderProducts = Product::query()->select('slider')->whereNotNull('slider')->get();
    $sliderServices = Service::query()->select('slider')->whereNotNull('slider')->get();

    $slideShows = $sliderProducts->concat($sliderServices);

    return view('Home.index', compact('slideShows'));
}

Or to execute a union query you can do

public function index()
{

    $sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
    $sliderServices = Service::query()->select('slider')->whereNotNull('slider');

    $slideShows = $sliderProducts
        ->union($sliderServices)
        ->get();

    return view('Home.index', compact('slideShows'));
}
  • Related