I'm new to Laravel and PHP in general and was wondering how I could paginate the tweets data in my example below:
Route::get("/users/{user}", function (User $user) {
return $user->only(
"id",
"name",
"username",
"avatar",
"profile",
"location",
"link",
"linkText",
"created_at",
"tweets"
);
});
The tweets
table is related to user
so I could say $user->tweets()->paginate(10);
but how can I return that along with my only()
method? also, is there a way for me to return multiple stuffs and can still access them on my frontend?
CodePudding user response:
You might want to look into API resources.
The only()
function is to be used after the query has completed, because it strips data from your model even though you have retrieved them from the database. Your call to tweets()
makes it a query object (without the ()
it would resolve to a collection object), so you are still able to chain query functions.
I suppose you could also call $user->tweets()->select(['id', 'user_id', 'body', ...])->paginate(10);
to only select the columns you need.
CodePudding user response:
If you want a more customizable pagination, you can try using limit
and offset
or skip
and take
then look into API Resource as suggested above