0
votes

I need to make pagination in Laravel, and as I read laravel documentation here is a several way to do it. but in my cases it is a little bit complexity. So let say I've two table in my DB, table1 and table2(many to many relationship), I want to paginate table1 with specific ids. So I mean if table1 contains ids 1,2,3,4,5 ... n, I want to paginate only rows which id is 2 and 3

I have tried :

private function check_wear($type){
        $products_id = array(); //here is ids which $type is set as 'ON'
        $wears = DB::select("SELECT prod_id FROM wears WHERE ".$type." = 'on' "); //Select specific products ids. (in our case it is **table1**)
        foreach ($wears as $wr){
            array_push($products_id,$wr->prod_id);
        }
        return $products_id; //return array with ids which should be paginate
    }
    public function hat($locale){

        $hat_prod_ids = $this->check_wear('coat');

        $p=12;
        $products = DB::table('products')->paginate($p); // 12 per page


        dd($products);

my code only paginate one table with all data, is there any built-in function to somehow write a logic condition? for pagination

1
In the line where you paginate, you just query the full table. You never use the $hat_prod_ids. And what do you expect from the line with the $full_items? Maybe also rethink your database design: you use 'ON', why not use a Boolean value (select where type = coat and enabled = true)Maarten Veerman
My question is exactly that, how use that $hat_prod_ids to filter my pagination.David J.
DB::table('products')->whereIn('id', $hat_prod_ids)->paginate($p); Check the whereIn function on the query builder.Maarten Veerman

1 Answers

0
votes

If you need to filter your pagination with elements which you've in $hat_prod_ids, you're able to use WhereIn() method, that one checks if your elements (in our case ids) exist in your $hat_prod_ids and returns true or false

$products = DB::table('products')
            ->whereIn('id',$hat_prod_ids)
            ->paginate($p);

add that code and now you will be able to paginate only that ids which is matched in your array