0
votes

I would like to paginate my results I get from my relationship. I have a products table/controller, a users table/controller and a markedProducts table. However, I don't have a markedProducts table because I don't actually need it. I use this solution to get all marked products of one user in my user model:

public function markedProducts(){    
    return $this->belongsToMany('App\Product', 'products_marks');
}

My question now is how can I paginate my results and my second question is how can I get the created_at value of each row in my markedProducts table?

Because my solution is only returning the marked products. However, I would like to show the user when he has marked the product.

So far I had this idea:

$markedProducts = DB::table('products_marks')->where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(2);
$products = Product::whereIn('id', $markedProducts->lists('product_id'));

However, ->lists() is not a method anymore and I actually don't want to bypass the Laravel methods and I don't want to loop through my pagination to get an array with all product_id's.

Do you guys have any good and performant solution?

Kind regards and thank you!

1

1 Answers

0
votes

Auth::user() will return the authenticated user.

And use relationship method markedProducts() to get the query of products.

And then orderBy the column created_at of pivot table.

At last, apply paginate to this eloquent builder.

Auth::user()->markedProducts()->orderBy('products_marks.created_at', 'DESC')->paginate($limit);