0

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.

Adam_R
  • 37
  • 2
  • 12

1 Answers1

1

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

Encang Cutbray
  • 382
  • 1
  • 2
  • 9
  • Can I also use this for sub as well? So would it effectively function as an AND if I used it afterwards? – Adam_R Sep 07 '20 at 14:23
  • Yes you can. ```when()``` method is really effective to handle ```$request->zone``` if not null, happy coding – Encang Cutbray Sep 07 '20 at 14:27
  • I changed it to the following ```public function all(Request $request){ $data = Maintain::all(); $data = Maintain::when($request->zone, function ($query){ $query->where('zone', $request->zone); })->get(); $data = Maintain::when($request->sub, function ($query){ $query->where('zone', $request->sub); })->get(); return $data; } ``` But it comes up saying that it can't find the `$request` variable – Adam_R Sep 07 '20 at 15:03
  • Thank you, but I updated it to what you suggested and it seems that it comes back with the error `ErrorException: Undefined variable: request` If I put `$request` into the function inside the `when` I get error: `ErrorException: Trying to get property 'zone' of non-object` – Adam_R Sep 07 '20 at 15:31
  • Yes, that has worked, thank you very much, I'm sorry about the extra questions, I didn't know you could pass variables in to the function with `use` – Adam_R Sep 07 '20 at 15:41
  • Ok no problem, happy coding – Encang Cutbray Sep 07 '20 at 15:45