0
0

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 1 year has passed since last update.

【Laravel】ヒアドキュメントを使ったSQLの実行

Last updated at Posted at 2022-12-17

Laravelで複雑なSQLを実行する際は、ヒアドキュメントを使用した方がわかりやすい場合があります。
以下は全く複雑なSQLではありませんが、基本となる記述方法になります。

use DB;

public function findUser($userId)
{
    $key = config('app.key');

    $sql = <<<SQL
SELECT
  user_id,
  CONVERT(AES_DECRYPT(UNHEX(first_name), ?)USING utf8) first_name,
  CONVERT(AES_DECRYPT(UNHEX(last_name), ?)USING utf8) last_name,
FROM
  users
WHERE
  user_id = ?
SQL;

    $userModel = DB::select($sql, [$key, $key, $userId]);
}

第二引数に配列で値を渡すことで、バインドパラメータを使用できる。
SQLの疑問符プレースホルダー(?)の数だけ用意してあげます。

DB::select($sql, [$key, $key, $userId])
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?