Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to return custom paging information with Resource in laravel

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to achieve custom paging information with Resource in laravel". In daily operation, I believe that many people in laravel have doubts about how to return custom paging information with Resource. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how to achieve custom paging information with Resource in laravel". Next, please follow the editor to study!

Why do you need it?

I'm basically developing API. In the early days, I always returned directly, but this approach sometimes has some problems and is not easy to maintain, coupled with the frequent need to add custom fields and give different data for different sides, I have been using Resource to define the returned data.

Using Resource is convenient and makes the logic clear. But there is a downside to it, that is, there is too much paging information. For API projects, in most cases, the default output of paging information in many fields are not needed, and because often docking with some old projects, the need to follow the old data format or do compatible, paging information fields are very different, there is no way to directly use the default paging information.

I don't know how you deal with paging information in similar situations, but before that, in order to achieve my goal, I usually have two ways: one is to customize the Response, which redefines the data information, and the other is to customize all the Resource-related classes.

I don't know much about the underlying Laravel, and I'm not good at abstract framework development, but after going through this, I found that things can become much easier, as I explained in PR, if you can build paging information in src/Illuminate/Http/Resources/Json/PaginatedResourceResponse.php, you can use the component paging information of its corresponding Resource class, then you don't have to go to a lot of trouble to customize a lot of classes at a time. So I submitted this idea to the Laravel framework. This submission was not directly accepted at first, but was merged after being adjusted by Taylor and released in v8.73.2.

This is the first time I have contributed code to Laravel and the first time I have submitted a merge request to such a large code base, and although it has not been adopted directly, the results are encouraging.

Use the example

So, let me give you a simple example of how to use it.

Default output {"data": [], "links": {"first": "http://cooman.cootab-v4.test/api/favicons?page=1"," last ":" http://cooman.cootab-v4.test/api/favicons?page=1", "prev": null, "next": null}, "meta": {"current_page": 1 "from": 1, "last_page": 1, "links": [{"url": null, "label": "«previous page", "active": false} {"url": "http://cooman.cootab-v4.test/api/favicons?page=1"," label ":" 1 "," active ": true}, {" url ": null," label ":" next page »" "active": false}], "path": "http://cooman.cootab-v4.test/api/favicons"," per_page ": 15," to ": 5," total ": 5}}

This is the default output of Laravel paging information, whether there are many fields, of course, this is sufficient for the use of many scenarios. But sometimes it makes it difficult. We need a little flexibility.

When using the ResourceCollection class

Let's first look at the underlying logic!

When the controller returns a ResourceCollection, its toResponse method is eventually called in response. Then you can find this method directly and take a look at:

/ * Create an HTTP response that represents the object. * * @ param\ Illuminate\ Http\ Request $request * @ return\ Illuminate\ Http\ JsonResponse * / public function toResponse ($request) {if ($this- > resource instanceof AbstractPaginator | | $this- > resource instanceof AbstractCursorPaginator) {return $this- > preparePaginatedResponse ($request);} return parent::toResponse ($request);}

See, if the current resource is a paging object, it turns the task to dealing with the paging response. Go on to see:

/ * Create a paginate-aware HTTP response. * * @ param\ Illuminate\ Http\ Request $request * @ return\ Illuminate\ Http\ JsonResponse * / protected function preparePaginatedResponse ($request) {if ($this- > preserveAllQueryParameters) {$this- > resource- > appends ($request- > query ();} elseif (! Is_null ($this- > queryParameters) {$this- > resource- > appends ($this- > queryParameters);} return (new PaginatedResourceResponse ($this))-> toResponse ($request);}

Oh, it is transferred to PaginatedResourceResponse, which is the class we finally need to modify. Because the content of toResponse is too long, it will not be posted here. Anyway, this is where we start to build the response data. Of course, the paging information is also processed here, but it has an independent method. The method is paginationInformation, which is the logic before submitting the PR:

/ * Add the pagination information to the response. * * @ param\ Illuminate\ Http\ Request $request * @ return array * / protected function paginationInformation ($request) {$paginated = $this- > resource- > resource- > toArray (); return ['links' = > $this- > paginationLinks ($paginated),' meta' = > $this- > meta ($paginated),];}

If you are careful, you should be able to think that the $this- > resource here is actually an example of the above ResourceCollection, then its resource is our list data, that is, the paging information instance. In that case, why can't we process paging information in ResourceCollection? Sure, but we need to add something, and that's the idea I submitted.

After merging PR, its logic looks like this:

/ * Add the pagination information to the response. * * @ param\ Illuminate\ Http\ Request $request * @ return array * / protected function paginationInformation ($request) {$paginated = $this- > resource- > resource- > toArray (); $default = ['links' = > $this- > paginationLinks ($paginated),' meta' = > $this- > meta ($paginated),] If (method_exists ($this- > resource, 'paginationInformation')) {return $this- > resource- > paginationInformation ($request, $paginated, $default);} return $default;}

It's a simple way to deal with it, and if there is a custom paging information composition method in the corresponding resource class, use its own, which is, for now, a really good idea.

At this point, how to customize the paging information should be clear. That is to add the paginationInformation method to your corresponding ResourceCollection class, such as:

Public function paginationInformation ($request, $paginated, $default): array {return ['page' = > $paginated [' current_page'], 'per_page' = > $paginated [' per_page'], 'total' = > $paginated [' total'], 'total_page' = > $paginated [' last_page'],];}

This is the data output after customization:

{"data": [], "page": 1, "per_page": 15, "total": 5, "total_page": 1}

It turned out to be what I wanted.

When using the Resource class

I usually only like to define a Resource class to deal with individual objects and lists, which focuses on how to handle paging customization of list data.

In the controller, I usually use it like this:

Public function Index () {/ /.... Return SomeResource::collection ($paginatedData);}

Let's look at what's done in the collection method:

/ * Create a new anonymous resource collection. * * @ param mixed $resource * @ return\ Illuminate\ Http\ Resources\ Json\ AnonymousResourceCollection * / public static function collection ($resource) {return tap (new AnonymousResourceCollection ($resource, static::class), function ($collection) {if (property_exists (static::class, 'preserveKeys')) {$collection- > preserveKeys = (new static ([]))-> preserveKeys = = true;}}) }

It turns out that it transfers the data to ResourceCollection, so all you need to do is customize the AnonymousResourceCollection.

Summary

This is a small optimization, but very useful.

Before that, if you want to return custom paging information with Resource, it will be troublesome and need to customize a lot of things. This way is a piece of cake for regular users, but it can be a thorny problem for beginners. From then on, it will be easy for both regular users and beginners. You just need to add the paginationInformation method to the corresponding ResourceCollection class, like this:

Public function paginationInformation ($request, $paginated, $default): array {return ['page' = > $paginated [' current_page'], 'per_page' = > $paginated [' per_page'], 'total' = > $paginated [' total'], 'total_page' = > $paginated [' last_page'],];}

However, if you are using the Resource::collection ($pageData) method, you need to customize an additional ResourceCollection class and override the collection method of the corresponding Resource class.

I usually define a corresponding base class, and then everything else inherits it. You can also make a trait and share it.

At this point, the study on "how to achieve custom paging information with Resource in laravel" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report