php - Laravel paginate belongsToMany relationship?

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 thecreated_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 allproduct_id
's.
Do you guys have any good and performant solution?
Kind regards and thank you!
Answer
Solution:
Auth::user() will return the authenticated user.
And use relationship methodmarkedProducts()
to get the query of products.
And thenorderBy
the columncreated_at
of pivot table.
At last, apply paginate to this eloquent builder.
Auth::user()->markedProducts()->orderBy('products_marks.created_at', 'DESC')->paginate($limit);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.