Laravel Database Inserts, Updates And Deletes
Laravel Database Inserts, Updates And Deletes – The Laravel Database Inserts, Updates And Deletes is used insert, update and delete the data from the database.
Laravel Database Inserts, Updates And Deletes.
Let us understand how to use Laravel Database Inserts, Updates And Deletes.
Function:-
There are some followings function available in Laravel Database Inserts, Updates And Deletes.
- 1. Inserts.
- 2. Updates.
- 3. Deletes.
- 4. Pessimistic Locking.
1. Inserts.
The query builder also provide an insert method for inserting records into the database table. This method accepts an array of column name and values.
DB::table('users')->insert( ['email' => 'sonu@example.com', 'name' => 0] );
You can even insert several records into the table with single call call of insert method but passing in array format.
DB::table('users')->insert([ ['email' => 'sonu@example.com', 'votes' => 0], ['email' => 'abhi@example.com', 'votes' => 0] ]);
Auto-Incrementing IDs
If the table has auto increment id, use the insertGetId method to insert a record.
$id = DB::table('users')->insertGetId( ['email' => 'sonu@example.com', 'votes' => 0] );
2. Updates.
The update method is used to update the record which is already inserted in the database.
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
Updating JSON Columns
When updating a JSON column, you should use -> syntax to access the key in the JSON object.
DB::table('users') ->where('id', 1) ->update(['options->enabled' => true]);
Increment & Decrement
The query builder also provides convenient methods for incrementing or decrementing the value of a given column. This is simply a shortcut, providing a more expressive and terse interface compared to manually writing the update statement.
DB::table('users')->increment('votes'); DB::table('users')->increment('votes', 5); DB::table('users')->decrement('votes'); DB::table('users')->decrement('votes', 5);
You can also specify additional columns to update during the operation.
DB::table('users')->increment('votes', 1, ['name' => 'John']);
3. Deletes.
The query builder can also be used to delete records from the database by using the delete method.
DB::table('users')->delete(); DB::table('users')->where('votes', '>', 100)->delete();
If you want to truncate the entire table which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method.
DB::table('users')->truncate();
4. Pessimistic Locking.
The query builder also includes a few functions to help you do “pessimistic locking” on your
select statements. To run the statement with a shared lock, you may use the shareLock method on a query.
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
You can also use lockForUpdate method.
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
Advertisements