Your code seems to be the right one.
You can perhaps add query().
Post::query()->pagination($request);
I have a request that should use simplePagination only if paginate is 0 in the query. if paginate doesn't exist or is any other value the response should use classic pagination. How can I achieve this in the code below.
Controller
public function index(Request $request){
Post::pagination($request);
}
Post Model
public function scopePagination($query, $request){
$query->when($request->paginate ==0, function($query){
$query->simplePaginate();
})->when($request->paginate !=0, function($query){
$query->paginate();
});
}
NB:: I know there is $request->has() but the code feels messy when I use that
I found a solution:
public function scopePagination($query, $request)
{
return $query->when(
in_array($request->paginate, ['0', 'false']),
fn($query) => $query->simplePaginate($request->limit ?? 12),
fn($query) => $query->paginate($request->limit ?? 12)->withQueryString()
);
}
@ben taylor Thanks, did not know you could add a second closure to when()
NB::I only used string values since 0==NULL or false==NULL is true in php
Please or to participate in this conversation.