COACHTHEM's avatar

Paginate() with custom data.

Here is my use case.

  1. I have to fetch blog data by writing sql query and the data needs to be paginated.
  2. The data fetched from above query needs to be looped to create image url for each blog.
  3. After looping each blog record I create a new dimensional array which has all the blog details along with image url

below is the code sample with which I want to fetch all blog data with process image url and I also expect it has pagination details like the total no of pages, current page etc.

public function getBlogs(Request $request) {

   $rawBlogs = DB::table('blogs')
   ->select(['id', 'title', 'content', 'status', 'blog_image'])
   ->where([
       ['status', '=',  'A']
   ])
   ->orderBy('id', 'DESC')
   ->paginate();

   $Blogs = [];
   foreach($rawBlogs-items() as $rawBlog){

       $blog_path = config('app.BLOG_IMAGE_PATH'); 
       $imgPath = $blog_path . $rawBlog->blog_image; 
       $Url = \Storage::url($imgPath); 

       $Blogs[] = [
           'id' => $rawBlog->id,
           'title' => $rawBlog->title,
           'content' => $rawBlog->content,
           'status' => $rawBlog->status,
           'blog_image' => $Url
       ];       

   }

   return [
    'data' => $Blogs,

    current_page => ?,
    first_page_url => ?,
    from => ?,
    next_page_url => ?,
    first_page_url => ?,
    path => ?,
    per_page => ?,
    prev_page_url => ?,
    total => ?  
];

}

0 likes
2 replies
mlewis's avatar

You should move this inside your Blog model (assume you have one) and simplify everything.

So you'd go something like

$blogs = Blog::where('status','A')->orderBy('id','desc')->paginate();

return ['data' => $blogs->toArray()];

Then in your Blog model, have something like this, using $appends property

protected $appends = ['blog_image_url'];

public function getBlogImageUrlAttribute() { 
   // In here stick your logic to form the url
}
jlrdw's avatar

Usually for image I:

        <tr>
            @if (empty($row->dogpic))
                <td class="imgtd">&nbsp;</td>
            @else
                <td class="imgtd"><img src="{{ asset('assets/upload/imgdogs') . '/' . $row->dogpic }}" alt="" class="image"></td>
            @endif
     

But any parameters have to be passed to paginato, if parameters in controller was:

$params = array('psch' => $dogsearch, 'aval' => $aval);

The view would be:

{{ $dogs->appends($params)->links }}

Would give something like:

site.com/dogs?page=4&psch=c&aval=1

Where $params are other query string parameters that are passed from page to page. Of course you retrieve the parameters on each new page request to use.

Please or to participate in this conversation.