0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】でトランザクションをはる方法

Last updated at Posted at 2021-08-17

Laravelでトランザクションを張る方法メモ

方法は2つ

  1. DBファサードのbeginTransaction()commit()rollBack()を使用する。
  2. DBファサードのtransaction()メソッドにクロージャを渡す。

1の方法

    public function create(Request $request)
    {
        try {
            DB::beginTransaction(); //トランザクション開始

            $author = Author::create($request->all());

            DB::commit(); //コミット

        } catch(\Exception $e) {

            DB::rollBack(); //ロールバック
        }
    }

beginTransaction()でトランザクションを開始して、問題がなければcommit()でコミット
例外が発生すればrollBack()でロールバックされる。

2の方法

    public function create(Request $request)
    {
        DB::transaction(function() use($request) {
            $author = Author::create($request->all());
        });
    }

問題がなく処理が実行されれば、自動的にコミットされる。
例外やエラーが発生した場合は自動的にロールバックされる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?