Home > Software engineering >  How to write multiple where conditions in single where condition in laravel?
How to write multiple where conditions in single where condition in laravel?

Time:11-09

I am using multiple where conditions in my query it's working fine but i need to refactor the code is there any way to write both conditions in one where condition..

DB::table('books')->where('user_id',$uID)->where('author',$author_name)->delete();

CodePudding user response:

Pass array of conditions to the where function.

DB::table('books')->where([['user_id','=',$uID],['author','=',$author_name]])->delete();

As per Doc :

pass an array of conditions to the where function. Each element of the array should be an array containing the three arguments typically passed to the where method

Ref:https://laravel.com/docs/8.x/queries#where-clauses

CodePudding user response:

Try this:

DB::table('books')->where(function($q){
    $q->where('user_id', $uID);
    $q->where('author',$author_name);
})->delete();

BTW you can change "DB::table('books')->" with "Book::" if you have Book model

CodePudding user response:

You can use array in where function like below -

Modelname::where([['user_id',$uID],['author',$author_name]])->delete();
  • Related