Background: The recent use of Laravel-5.4 for project development involves data manipulation of the associated model and the thought of rolling back with a transaction. The middle involves the data reference and the catch of the exception.
There are two ways to roll back a database transaction: automatic rollback, manual rollback.
Examples are as follows:
Automatic rollback
function (request $request) { db::transaction (function () use ($request) { try { $admin = admin::create ([' Name ' => $request->name, ' password ' => encrypt ($ Request->password), ' email ' => $request->email]); $admin->roles ()->attach ($request->role_id); // $admin->roles ()->attach (' SD ');//intentional input of the wrong parameter type, commit failed return ' Success '; } catch (\exception $exception) { return $exception->getmeSsage (); } }); }
You need to request data $request using the use reference. Otherwise the error "Undefined variable:request"
Manual rollback
function (request $request) { db:: BeginTransaction (); try { $admin = admin::create ([' Name ' => $request- >name, ' Password ' => encrypt ($request->password), ' email ' => $ Request->email]); $admin->roles () ->attach ($request->role_id); db::commit (); return ' success '; } catch (\exception $exception) { db::rollback (); return $exception->getmessage (); } }
Laravel database Transaction Rollback