mercredi 18 juillet 2018

Starting Query Builder without using a query

So, I can use User::where('username', '!=', null)->get();

However, I am in a case where I want to chain queries using if conditions starting from the first one, and where('username', '!=', null) is unnecessary in this case. Let me give a pseudo example:

I am running a report based on Users where there are several fields. I want to initialize the query builder like this, and chain queries using if statements.

$user = User::class();   // I know I can't use this line, however you'll get the idea.

if (isset($gender)) {
   $user = $user->where('gender', $gender);
}

if (isset($age)) {
   $user = $user->where('age', $age);
}

$users = $user->get()

Is the only way starting the query (in the first line) with:

$user = User::where('username', '!=', null)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire