Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 update all records in table without using where clause

Tags:

php

mysql

laravel

I am trying to update all records from table withing single eloquent query in Laravel 5.4

Currency::update(['default'=>0]);

I am expecting that this query will update all the records from a table, but this query isn't working. It is expecting where clause and I don't want to put any conditions using where clause, I just want to update all records in a table.

I am not getting any answer from laravel documentation.

Table Structure enter image description here

like image 981
Vishal Shetty Avatar asked Oct 10 '17 02:10

Vishal Shetty


People also ask

How to update data from MySQL database using Laravel framework php?

Update data from database using Laravel framework. In this example we will discuss about how to update a record or data from MySQL database using laravel framework PHP. To update the data in mysql table UPDATE statement is used. SET column1=value, column2=value2,... Note: The WHERE clause specifies which data that should be updated.

How to update multiple records in Laravel?

This function is used to update the multiple records in Laravel. You just need to define what you want to update in first argument but with some unique fields, and in second argument define the which fields are unique for update and in third argument list out the fields which will actually be updated in the database.

What is the use of save () method in Laravel?

As the name suggest, the save () method is used to save the records. In this method, first we need to find the record and then we can add additional data into it and then we save the records. Thus, it will update the records in database.

What is upsert () function in Laravel?

The upsert () is very interesting function in Laravel. This function is used to update the multiple records in Laravel.


3 Answers

MySQL has a safe update server mode which will not allow an update to happen unless the statement has a WHERE clause involving the primary key. If your MySQL be running in this mode, then one way to spoof it would be to use WHERE id = id, something like this:

DB::table('Currency')
        ->where('id', 'id')
        ->update(['default' => 0]);
like image 190
Tim Biegeleisen Avatar answered Nov 03 '22 21:11

Tim Biegeleisen


Product::query()->update(['default' => 0, ]);

Simple query to update all rows of the table.

like image 29
Aftab Khaliq Avatar answered Nov 03 '22 23:11

Aftab Khaliq


If your MySQL server running SQL_SAFE_UPDATES mode you can use "where" like this. Or another "where clause" that includes all results.

Currency::where('id', '>', 0)->update(['default' => 0]);
like image 41
Okan Avatar answered Nov 03 '22 22:11

Okan