LoginSignup
2
3

More than 5 years have passed since last update.

Eloquentを単体で導入している時にDBファサードを使用する方法

Last updated at Posted at 2018-03-28

概要

FacadeはLaravelなら初期状態でも使用できるが、Eloquentをスタンドアロンパッケージとして導入している場合はひと手間必要。

そのままFacadeを使おうとすると

RuntimeException: A facade root has not been set.
が発生してしまう。

接続設定

Eloquentを導入している次点で接続設定は行っているはずだが念の為。
リクエスト~ルーティングの間等に接続設定を記述しておく。

接続設定
$db = new \Illuminate\Database\Capsule\Manager;
$db->addConnection([
    // setting
]);
$db->setAsGlobal();
$db->bootEloquent();

使用方法

DBファサードを使用したいクラスで以下のように記述する。

TestController,php
use \Illuminate\Database\Capsule\Manager as DB;

// 省略

try {
    $con = DB::connection();
    $con->beginTransaction();

    // transaction処理

    $con->commit();

} catch (\Exception $e) {
    $con->rollBack();
    echo $e->getMessage();
}

参考

2
3
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
2
3