Reputation: 47
I'm currently trying to get data from the DB with a Laravel controller through a model Maintain
. Is there a way to query the DB based on the request data made by an axios post from the front end, this includes both variables sub
and zone
, I have the ability to get the data from using sub
OR zone
but not both, is there a way to construct a multi where query if $request
contains the necessary variables and a standard request if they are null
or ""
?
public function all(Request $request){
$query = [];
if($request->sub != ""){
array_push($query, ['subsystem', '=', $request->sub]);
}
if($request->zone != ""){
array_push($query, ['zone', '=', $request->zone]);
}
if(count($query) > 0){
return Maintain::all()->where($query);
}
else{
return Maintain::all();
}
}
Currently This returns with an error ErrorException: array_key_exists(): The first argument should be either a string or an integer in file
but I've been using the Laravel reference and it doesn't seem to be working. I used Postman to get the readout of $query
and it contains the following:
[
['sub', '=', 'Subsystem 1'],
['zone', '=', 'Zone 1']
]
Any help would be appreciated.
Upvotes: 0
Views: 36
Reputation: 392
Try like this
public function all(Request $request){
$result = Maintain::when($request->zone, function ($q) use($request){
$q->where('zone', $request->zone);
})
->when($request->sub, function ($qw) use($request){
$qw->where('subsystem', $request->sub);
})
->get();
return($result);
}
when()
method look like if-else
Edited: Let we know if you get an error: Happy coding
Upvotes: 1