7

Rollback Transaction With Laravel Eloquent

 3 years ago
source link: https://www.codewall.co.uk/rollback-transaction-with-laravel-eloquent/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Rollback Transaction With Laravel Eloquent

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK