Home > Blockchain >  Pagination in Laravel return tables value but not all value of paginate()
Pagination in Laravel return tables value but not all value of paginate()

Time:06-01

This is my api which is testing in Postman. It returns value but not pagination value.

http://localhost/api/v1/projects-data  //This is api

here is the image of data which its return to Postman here is the image of data which its return to Postman

I put the route code in api.php

Route::get('all-blogs', 'Api\ApiController@getBlogs');

And at last in my ApiController.php

public function getBlogs(Request $request, Blog $blog = null)
{
    
    if ($blog != null) {
        $blog = Blog::with(['tag', 'comments', 'user'])->where('slug_en', $blog->slug_en)->firstOrFail();
        $blog->increment('views');

        return response()->json(BlogResource::make($blog));
    }
    $blogs = Blog::with([
        'tag', 'comments', 'user',
    ])->orderBy('created_at', 'desc')->paginate(5);
    
    return response()->json(BlogResource::collection($blogs));
}

And code on BlogResource.php

public function toArray($request)
{
    
    return [
        'id'=>$this->blog_id,
        'keyword' => $this->keyword,
        'description' => $this->description,
        'title' => $this->title,
        'content' => $this->content,
        'content_bare' => strip_tags($this->content, 'ul,li,ol,p,br,h1,h2,h3,h4,h5,h6,b,a,span,table,thead,tr,th,td,tfoot,tbody,i,em,strong,strike'),
        'image_url' => $this->image_url,
        'slug' => $this->slug_en,
        'views' => $this->views,
        'created_at' => date('d M Y', strtotime($this->created_at)),
        'ago' => $this->created_at->diffForHumans(),
        'comments' => $this->whenLoaded('comments'),
        'user' => $this->whenLoaded('user'),
        'tag' => $this->whenLoaded('tag'),
    ];
}

Every Thing working when i put paginate(5). it's return 5 data in Postman. But Not return other information like current_page , first_page and so on is not showing.

I need this type of output return

I need this type of output return

CodePudding user response:

The problem here is that you are using return response()->json($resource), if you return just the resource (return $resource) it will be returned as a JsonResource and the pagination metadata will be shown.

CodePudding user response:

You are applying pagination on the $blogs variable if you return that variable that will give you paginated answers as you want like page links etc. Currently you are returning resource thats why you are not getting the desired answer.

CodePudding user response:

$list = BlogResource::collection($blogs);
$statisticCollection = collect($list);
$sorted = $statisticCollection->paginate(5);
return $sorted;
  • Related