Home >Backend Development >PHP Tutorial >Transactions in Laravel
On certain occasions, we need to carry out a series of consecutive operations, and it is essential that all of them are completed successfully, without any being left half done.
A common example is the creation of a user, where it is essential that roles are also assigned and a registration email sent.
To handle these types of situations, transactions are used. Here is a method that creates a user, assigns the role, and then sends an email via the sendEmail() method. This method receives the email as an argument and sends it accordingly.
use Illuminate\Support\Facades\DB; public function save(array $data) { try { $user = User::create($data); $user->syncRoles([$data['role']]); $this->sendEmail([ 'email' => $data['email'], ]); return $user; } catch (\Exception $e) { throw new BadRequestException("Error al guardar nuevo usuario"); } }
We must apply 3 methods:
Implementing transactions in the previous code we are left with:
use Illuminate\Support\Facades\DB; public function save(array $data) { // Iniciar la transacción DB::beginTransaction(); try { $user = User::create($data); $user->syncRoles([$data['role']]); $this->sendEmail([ 'email' => $data['email'], ]); // Confirmo la transacción DB::commit(); return $user; } catch (\Exception $e) { // Si falla hago rollback DB::rollback(); throw new BadRequestException("Error al guardar nuevo usuario"); } }
With this we ensure that the set of operations are executed completely or not at all.
Laravel also provides another more concrete transaction method of the DB facade. In this case the commit and rollback are done automatically. This is recommended when the number of operations is few or does not require additional operations before performing the rollback
DB::transaction(function () use($data){ $user = User::create($data); $user->syncRoles([$data['role']]); $this->sendEmail([ 'email' => $data['email'], ]); return $user; });
Important: Database Engine Considerations
Not all storage engines support transactions. InnoDB is an engine that does support transactions, while MyISAM does not. It is essential to ensure that your database tables are using an engine that supports transactions for them to function correctly.
The above is the detailed content of Transactions in Laravel. For more information, please follow other related articles on the PHP Chinese website!