Сергей
Сергей

Reputation: 7

How to add and exclude where() clause in laravel query builder

How to add and exclude where() clause in laravel query builder so that in one case it will be added in other one no

$orders =  DB::table('orders')->select(
'orders.id as id',
'orders.created_at as created',
    'u.email as email',
    'ud.id as data_id',
    'ud.firstName as firstName',
    'ud.lastName as lastName',
    'ud.phone as phone',
    's.name as service',
    's.id as service_id',
    'pt.id as payment_type_id',
    'pt.name as payment_name')
    ->join('users as u', 'orders.user_id', '=', 'u.id')
    ->join('user_data as ud', 'u.id', '=' ,'ud.user_id')
    ->join('payment_types as pt', 'orders.payment_type_id', '=', 'pt.id')
    ->join('services as s', 'orders.service_id', '=', 's.id')
    ->where('u.id', $user->id)->orderBy($sortBy, $type)->get();

I want to do this

$order = DB::table()....
if(true){
  $order->where('id', '=', 1);
}
$order->orderBy('fieldname', 'asc')->get();

But the example above return no results

Upvotes: 0

Views: 299

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14271

For conditional clauses you can make use of when().

$order = DB::table()
       ->yourQuery(...)
       ->when($var, function ($query, $var) {      // <----
           return $query->where('id', '=', 1);     // <----
       }                                           // <----
       ->orderBy('fieldname', 'asc')
       ->get();

You can read more about this in the docs:

Conditional Queries

Sometimes you may want clauses to apply to a query only when something else is true. For instance you may only want to apply a where statement if a given input value is present on the incoming request. You may accomplish this using the when method:

$role = $request->input('role');

$users = DB::table('users')
            ->when($role, function ($query, $role) {
                return $query->where('role_id', $role);
            })
            ->get();

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

...

Upvotes: 1

Related Questions