Pass variable to Api Resource Collections

Published 4 months ago by jlanzas

Is there anyway I can pass variable to a resource collection? I have been looking around but can't figure it out.

Any help will be greatly appreciated.

martinbean

@jlanzas You shouldn’t really need to. Resources are meant to change how a model is displayed. You shouldn’t be passing additional data to it.

skliche
skliche
4 months ago (149,490 XP)

What exactly are you trying to do/achieve?

jlanzas

Thank you for the answers guys... @skliche I'm working with datatables and pagination. So I need to send back, the page number, total pages, item count, per-page amount, sort field and sort order.

I can get a few fields like the item count, total pages, but the page number is send on a variable the same goes for the per-page amount and the sorting field and order.

So thats the reason I want to send those fields to the ResourceCollection.

skliche
skliche
4 months ago (149,490 XP)

You can add both meta data and pagination information. Did you look at https://laravel.com/docs/master/eloquent-resources#adding-meta-data and https://laravel.com/docs/master/eloquent-resources#pagination?

You can overwrite the default constructor (public function __construct($resource)) if you need to pass additional data at that point.

Please sign in or create an account to participate in this conversation.