Speakeroc
Speakeroc

Reputation: 60

Laravel Link data queries and pagination

How can I combine 3 requests into one to process it through "foreach" and display it with pagination?

$data['diamond_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 1)->orderByDesc('date_added')->get();
$data['vip_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 1)->orderByDesc('date_added')->get();
$data['default_ads'] = AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 0)->orderByDesc('date_added')->get();

Upvotes: 0

Views: 42

Answers (2)

Abdullah Ibn Farouk
Abdullah Ibn Farouk

Reputation: 133

I wrote this query , give it a try

AdModel::where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)
        ->where(function($query){
            $query->where('ad_diamond', '=', 1);
            $query->orWhere(function ($query) {
                $query->where('ad_vip', '=', 1);
                $query->where('ad_diamond', '=', 0);
            });
            $query->orWhere(function ($query) {
                $query->where('ad_vip', '=', 0);
                $query->where('ad_diamond', '=', 0);
            });
        })->orderByDesc('date_added')->paginate();

Upvotes: 1

Amir Abouei
Amir Abouei

Reputation: 128

As you use three separate queries and now you want to combine them, you can use all your queries in on query and handle that with orWhere in laravel like this:

AdModel::where(function (Builder $query){
        $query->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 1);
      })->orWhere(function(Builder $query){
        $query->where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 1)
      })->orWhere(function(Builder $query){
        $query->where('status', 1)->where('moderation','=', 0)->where('category_id', '=', $this_category_id)->where('ad_diamond', '=', 0)->where('ad_vip', '=', 0)
      })->orderByDesc('date_added')->paginate();

Upvotes: 0

Related Questions