Many times during application development you may wish to update column value/s or attributes in Laravel.
In this tutorial, lets check out the best ways to update Laravel records.
Suppose you have a table
posts with multiple columns. Now, for some reason, you may want to update the
views column of a single post where
id is 5. You can do this in few ways.
Raw function for updates
To update a specific column, first search the specific column with the value to be updated.
$posts = App\Post::where('id', 5)->update([ 'visits' => \DB::raw('views+1') ]);
The code above shows, that we search the post with id of 5 is and then apply update clause on it. The method DB::raw() (from the use Illuminate\Support\Facades\DB) allows you to select whatever column name you want and write raw SQL statements.
You can use raw queries for all types of SQL statements, whether its a select, insert or update. An example is shown below.
...->update( array( 'column_name' => DB::raw( 'column_name* 2' ) ) );
Increment function for update
An alternate way to update columns is to use the increment() function.
$posts = App\Post::where('id', 1)->increment('views', 1);
In this case, if you want to find more than 1 post and try to update the
views column. You can use the increment() function from above for updating more than 1 record.
This function can update 1 or more records. Consider the example below to update column values of many records.
$posts = App\Post::whereIn('id', [1,2,3,4,5])->update([ 'visits' => \DB::raw('views+1') ]);