kuns25's avatar

How to use Laravel pagination in loop

Hello everyone, I am trying to store my API resource response in .json file. I'm having two issue i don't how i can get data of next page in the loop and the second issue is i cant store data of $response in .json file until i write $response->toJson() . but this for some reason removes meta data

        $posts =  Post::paginate(10);

        for ($i=1; $i <= $posts->lastPage(); $i++) {
			// get posts from 2nd page and so on.. 
            $response =    PostApiResource::collection($posts);
            return   Storage::disk('local')->put("posts{$i}.json", $response);
        }

please help. Thanks

0 likes
11 replies
kuns25's avatar

@jlrdw I am not going to display paginated data from this endpoint. I'm just trying to create.json a file from my controller that's it

kuns25's avatar

@jlrdw yes brother I'm using API resources I'm getting perfect responses, I want to extract that response in a JSON file

jlrdw's avatar

@kuns25 json is text just write it to a file, no different than any text you write to a file.

Just curious, why write it to a file.

kuns25's avatar

@jlrdw I need to share the .json file with my client and the pagination has 3000+ pages, it would be great if I can automate this thing

            Storage::disk('local')->put('test.txt', 'my-text'); // this works  

            $response =  PostApiResource::collection($posts);
            Storage::disk('local')->put("posts{$i}.json",$response);  // this creates the file with no data in it but when I return $response it has data in it.

MohamedTammam's avatar

To convert a model to JSON, you should use the toJson method

Read more on the docs

jlrdw's avatar

@kuns25 I still don't understand why you need to write it to a file, just include pagination in your results and a client can view it directly.

kuns25's avatar

Alright guys I end up doing it in a creepy way , but as long as it works

        $posts =  Post::select('id')->paginate(10);
        for ($i=1; $i <= $posts->lastPage(); $i++) {
            $response =  Http::get("http://dev.my-domain.com/api/posts?page={$i}")->json();
            Storage::disk('public')->put("posts/posts{$i}.json", json_encode($response));
        }

kuns25's avatar
kuns25
OP
Best Answer
Level 6

Even better approach to call API internally

       $request = Request::create('/api/posts?page=1', 'GET');
        $res = app()->handle($request)->getContent();
        return    Storage::disk('public')->put("posts/posts1.json", $res);

Please or to participate in this conversation.