Call to undefined method Spatie\QueryBuilder\QueryBuilder::mapInto()
alitokmakci opened this issue · comments
spatie/laravel-query-builder v: 5.0.2
laravel v: 9.14.1
php v: 8.0.2
Hi! I want to create an api, if user sends page or per_page parameters api should paginate or if user do not send these parameters api should return all the data. When I tried the given code it gives error below:
Call to undefined method Spatie\QueryBuilder\QueryBuilder::mapInto()
// Not Working
$query = District::query();
QueryBuilder::for($query)
->allowedFilters([
'name',
'is_active',
AllowedFilter::exact('city_id')
])
->allowedIncludes([
AllowedInclude::relationship('city'),
AllowedInclude::count('storesCount'),
]);
if (request()->has('page') || request()->has('per_page')) {
$districts->paginate(
perPage: request('per_page', 15),
page: request('page', 1)
);
} else {
$districts->get();
}
return new DistrictCollection($districts);
Here are the working examples:
// Working example
$query = District::query();
QueryBuilder::for($query)
->allowedFilters([
'name',
'is_active',
AllowedFilter::exact('city_id')
])
->allowedIncludes([
AllowedInclude::relationship('city'),
AllowedInclude::count('storesCount'),
])->get();
return new DistrictCollection($districts);
// Working example 2
$query = District::query();
QueryBuilder::for($query)
->allowedFilters([
'name',
'is_active',
AllowedFilter::exact('city_id')
])
->allowedIncludes([
AllowedInclude::relationship('city'),
AllowedInclude::count('storesCount'),
])->paginate(
perPage: request('per_page', 15),
page: request('page', 1)
);
return new DistrictCollection($districts);
Problem solved when I changed to this:
if (request()->has('page') || request()->has('per_page')) {
$districts = $districts->paginate(
perPage: request('per_page', 15),
page: request('page', 1)
);
} else {
$districts = $districts->get();
}
Sorry for taking your time that was totally my sleepy mistake!