Hello,
In Laravel 6 I make pagination listing like
$ads = Ad
::getByTitle($this->filter_title)
->getByStatus('A')
->leftJoin('users', 'users.id', '=', 'ads.creator_id')
->orderBy($this->order_by, $this->order_direction)
->select(
'ads.*',
'users.name as creator_username',
'users.email as creator_email',
'users.phone as creator_phone'
)
->offset($limit_start)
->take($ads_per_page)
->distinct()
->paginate($ads_per_page);
return (new AdCollection($ads));
and it works ok for me and in meta of returned data I got additive params including total :
meta":{"current_page":1,"from":1,"last_page":2,..."to":4,"total":5,"version":"1.0.3"}}
But I got a problem I added map to this request like:
$ads = Ad
::getByTitle($this->filter_title)
->getByStatus('A')
->leftJoin('users', 'users.id', '=', 'ads.creator_id')
->orderBy($this->order_by, $this->order_direction)
->select(
'ads.*',
'users.name as creator_username',
'users.email as creator_email',
'users.phone as creator_phone'
)
->offset($limit_start)
->take($ads_per_page)
->distinct()
->paginate($ads_per_page)
->map(function ($adItem) {
$adImage= AdImage
::getByAdId($adItem->id)
->getByMain(true)
->first();
if ($adImage) {
$adItem->main_image= $adImage->image;
$adItem->main_image_info= $adImage->info;
}
$categories = AdCategory
::getByAdId($adItem->id)
->leftJoin('categories', 'categories.id', '=', 'ad_categories.category_id')
->orderBy('category_name', 'desc')
->select(
'ad_categories.category_id as category_id',
'categories.name as category_name',
'categories.slug as category_slug'
)
->get()
->toArray();
$adItem->categories= $categories;
return $adItem;
})
->all();
as I lost all meta data. Why error and if there is a way to fix it?
In app/Http/Resources/AdCollection.php I have :
<?php
namespace App\Http\Resources;
use App\library\MyFuncsClass;
use Illuminate\Http\Resources\Json\ResourceCollection;
class AdCollection extends ResourceCollection
{
public static $wrap = 'ads';
public function toArray($request)
{
return $this->collection->transform(function($ad){
return [
'id' => $ad->id,
'title' => $ad->title,
'slug' => $ad->slug,
'phone_display' => $ad->phone_display,
'published' => $ad->published,
'price' => $ad->price,
'ad_type' => $ad->ad_type,
'expire_date' => $ad->expire_date,
'description' => $ad->description,
'creator_id' => $ad->creator_id,
'creator_username' => !empty($ad->creator_username) ? $ad->creator_username : null,
'creator_email' => !empty($ad->creator_email) ? $ad->creator_email : null,
'creator_phone' => !empty($ad->creator_phone) ? $ad->creator_phone : null,
'categories' => !empty($ad->categories) ? $ad->categories : [],
'main_image' => $ad->main_image,
'main_image_info' => $ad->main_image_info,
'created_at' => $ad->created_at,
'updated_at' => $ad->updated_at,
];
});
}
public function with($request)
{
return [
'meta' => [
'version'=>MyFuncsClass::getAppVersion()
]
];
}
}
Thanks!