I want to query an eloquent method and later paginate. So I have written the code as
$roles = Role::find();
if (!empty($request->get("globalFilter"))){
$roles->where('name','LIKE','%' . $request->get("globalFilter"). '%');
}
return response()->json($roles->paginate($request->get("perPage")));
The above throws the following error
too few arguments on function builder find
How can I still call where
and paginate
in my query above?
First you have to pass one value to find()
method as parameter.So that it will return one record based on given id .If you dont have id and want to fetch first record then you have to use first()
.
Also you are using paginate to return result ,i think you don't need find() method.
It should be
$roles = Role::query();
if (!empty($request->get("globalFilter"))){
$roles->where('name','LIKE','%' . $request->get("globalFilter"). '%');
}
$result=$roles->find($id);
or you can use if condition inside where callback like below
$roles = Role::where(function ($query)use($request){
if(!empty($request->globalFilter)){
$query->where('name','LIKE','%' . $request->get("globalFilter"). '%');
}
})->find($id);
or you can use when
to make query simpler
$roles = Role::when((!empty($request->globalFilter)),function($query)use($request){
$query->where('name','LIKE','%' . $request->get("globalFilter"). '%');
})->find($id);
Note: for find()
method you have to pass one parameter as id
or you have to use first()
.Both return one record.For multiple records you can use all()
or get()
Ref for when clause:https://laravel.com/docs/8.x/queries#conditional-clauses
Ref for first() and find():https://laravel.com/docs/8.x/queries#retrieving-a-single-row-column-from-a-table
If you are looking for return all roles where name like then you can do the following
$roles = Role::when((!empty($request->globalFilter)),function($query)use($request){
$query->where('name','LIKE','%' . $request->get("globalFilter"). '%');
})->paginate($request->get("perPage"));