Adam
Adam

Reputation: 507

If request is not null statement in Eloquent

How to execute statement in query only if request exists? Example: $request->type (if NULL search everywhere if not check only arriving filghts)

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->if($requst->type = NULL) return all; else { ->where('type', $request->type)
               ->get();

Thank you for help! :)

Upvotes: 2

Views: 1009

Answers (1)

Carlos Salazar
Carlos Salazar

Reputation: 1898

You can split your code reasigning the query like

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc');
if($requst->type != NULL) {
    $flights = $flights->where('type', $request->type);
}
return $flights->get();

Upvotes: 4

Related Questions