15
13

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 5 years have passed since last update.

LaravelでDB処理を書くときに気を付けたいこと

Posted at

DBの処理を書くときに気を付けたいのがトランザクション処理ですが、Laravelを触る時は皆さんどう書いてますかね?

今の現場で以下のように書いている人がいたので、これがベストプラクティスなのか気になって調べてみた。

try
{
    // InsertとかupdateとかのDB処理
} catch(exception e) 
{
    // エラー内容の表示
}

Laravelの場合、これはベストプラクティスではなくDB::transactionを使う方が良さ気です。

参考URL:
http://forumsarchive.laravel.io/viewtopic.php?id=1464
http://localdisk.hatenablog.com/entry/2013/12/29/Laravel_%E3%81%A7%E3%83%88%E3%83%A9%E3%83%B3%E3%82%B6%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3

DB::transactionを使うとエラーになった場合自動でロールバックまで行ってくれるので便利ですねー!

なので、LaravelでDB処理を書く際は以下のように書くのが良いみたいです。

$table = Table::find(1);
DB::transaction(function() use($table) {
    // InsertとかupdateとかのDB処理
    $table->save();
});

こっちの方がかなりスッキリ記述できますね!

一つ注意点として
DB処理以外をDB::transactionの中に書かないこと

15
13
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
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?