Rolling back queries is always a safeguard for your data if there were to be any errors during database manipulation. For example, during the execution of multiple delete commands or similarly, a save command in use with an update use-case. Laravel comes out-of-the-box with the Rollback functionality and is particularly very simple to use.
The answer to rolling back eloquent queries is to use a static DB::transaction
call, wrapped around your database execution code. This addition to your standard controller code looks like the following ‘wrapper function’.
DB::transaction(function () use ($product) { // Start the transaction
// Do stuff here
}); // End transaction
You can pass in variables using the use
operator so you don’t have to wrap all of your code inside of the transaction.
In the following example, I will demonstrate the rollback safeguard around saving (Updating) a database record using a generic update controller function call.
Example
public function update(Request $request, $id)
{
$product = Product::findOrFail($id);
// Validate the inputs
$request->validate([
'name' => 'required',
]);
$product->name = $request->get('name');
DB::transaction(function () use ($product) { // Start the transaction
$product->save();
}); // End transaction
return view('products.index');
}
And that is literally it, the magic transaction function will take note of any changes to the database and if there is a fault, it will simply roll back to the original state. Another Laravel Eloquent life-saver, quick and easy to use and does the job effectively.
The post Rollback Transaction With Laravel Eloquent appeared first on Code Wall.
This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here