Sai Tarun
Sai Tarun

Reputation: 594

How to write multiple where conditions in single where condition in laravel?

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();

Upvotes: 0

Views: 80

Answers (3)

Sushant Malvadakar
Sushant Malvadakar

Reputation: 21

You can use array in where function like below -

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

Upvotes: 1

John Lobo
John Lobo

Reputation: 15329

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

Upvotes: 3

mrobbizulfikar
mrobbizulfikar

Reputation: 461

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

Upvotes: 0

Related Questions