Transactions in Laravel

Susan Sarandon
Release: 2024-10-22 08:07:02
Original
414 people have browsed it

Transacciones en 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");
   }
}
Copy after login

We must apply 3 methods:

  • DB::beginTransaction(); Start a transaction
  • DB::commit(); Confirm the changes
  • DB::rollback(); In case any operation cannot be performed, it will revert all changes making the state the same as before the start of the transaction.

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");
     }
 }
Copy after login

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;
});
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!