Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete records based on the multiple where conditions as an array in laravel

I am searching in docs and in the stack exchange for days that, is there any way that I can actually pass an array with multiple conditions in it to delete the record in the Laravel 4.2?

Example

I want to achieve something like below

DELETE FROM `employees` WHERE user_id = 5 AND dept_id = 5

For this can I do something like below?

$whereArray = array('user_id'=>5,'dept_id'=>5);

return DB::table('employees')->where($whereArray)->delete();

I know I can use multiple where conditions to achieve this. But for every time a new condition arrives I have to rewrite the function. And also I cannot use this function as dynamic one.

So please help me this? How can achieve this using the array?

like image 689
Kiran Avatar asked Dec 11 '22 00:12

Kiran


1 Answers

You can't directly pass in the array, but you could process the array:

$whereArray = array('user_id' => 5,'dept_id' => 5);

$query = DB::table('employees');
foreach($whereArray as $field => $value) {
    $query->where($field, $value);
}
return $query->delete();

This functionality can be extracted out into a function, or even a model scope, that accepts your array and builds and returns the query to you.

For example, if you have an Employee model:

class Employee extends Eloquent {

    public function scopeWhereArray($query, $array) {
        foreach($array as $field => $value) {
            $query->where($field, $value);
        }
        return $query;
    }

}

Then you could do:

$whereArray = array('user_id' => 5,'dept_id' => 5);

return Employee::whereArray($whereArray)->delete();

Edit

If you wanted to be able to supply the operator, as well, you'd just need to change the format of your array:

$whereArray = array(
    array(
        'field' => 'user_id',
        'operator' => '=',
        'value' => 5
    ),
    array(
        'field' => 'dept_id',
        'operator' => '=',
        'value' => 5
    ),
    array(
        'field' => 'salary',
        'operator' => '<',
        'value' => 5000
    )
);

return Employee::whereArray($whereArray)->delete();

And you would need to update your function:

class Employee extends Eloquent {

    public function scopeWhereArray($query, $array) {
        foreach($array as $where) {
            $query->where($where['field'], $where['operator'], $where['value']);
        }
        return $query;
    }

}
like image 131
patricus Avatar answered May 04 '23 06:05

patricus