How To Update Data To Database With Example In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

How to Update Data to Database in Laravel

To update data from table we use SQL Update statement

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition

To learn more about SQL, please visit our BajarangiSoft site.

How to Update data in laravel
Let's see
Update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this

class UserController extends Controller
{
    public function update(Request $request,$id)
    {
        $user = DB::table('users')->where('id', $id)->update(['name' => 'kiran']);

        return 'Update data successfully';
    }
}
?>


Updating JSON Columns:When updating a JSON column, you should use -> syntax to access the appropriate key in the JSON object.

$user = 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.

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);
You may also specify additional columns to update during the operation:

DB::table('users')->increment('votes', 1, ['name' => 'kiran']);

Related Post