I want to update all users in my database with an age value which I get from my request. How do I manage this? I somehow need the current value in the db and multiple it.
DB::table('customers')
->update([
'age' => DB::raw('column1 * 2'),
]);
Advertisement
Answer
Let’s assume that the name of the field in your $request is multiple, you can iterate over your customer records and update each of them, applying your multiple value to their age:
// grab the `multiple` value from your request
$multiple = $request->get('multiple');
// get all your customers, loop over them and update each record
Customer::all()->each(function ($customer) use ($multiple) {
$customer->update(['age' => $customer->age * $multiple]);
});
If you want to use the QueryBuilder rather than Eloquent, then you can do the following:
DB::table('customers')->get()->each(function ($customer) use ($multiple) {
DB::table('customers')
->where('id', $customer->id)
->update(['age' => $customer->age * $multiple]);
});