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
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.
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.
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.
The upsert () is very interesting function in Laravel. This function is used to update the multiple records in Laravel.
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]);
Product::query()->update(['default' => 0, ]);
Simple query to update all rows of the table.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With