LoginSignup
1
0

More than 3 years have passed since last update.

【Laravel】routes.phpでDBから値を取得する

Posted at

routes.phpからレコードの値を取ってきてそのままviewへ表示させたい、という部分があったので、メモ程度に書きます。

環境

PHP : 5.6.30
MySQL : 10.1.21
Laravel : 5.1.46

テーブル

以下サンプルテーブルです。
wordsテーブル

id message
1 Hello
2 こんにちは

コード

route.php
Route::get('/', function () {
  // cookieからidを設定する
  if ($_COOKIE['lang'] == 'en') {
    $id = 1;
  } else {
    $id = 2;
  }

  // DB::table()を使用して値を取得する
  $query = DB::table('words')
    ->select('message')
    ->where('id', $id)
    ->first();

  $message = $query->message

   return view('main',['message' => $message]);
}
main.blade.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {{$message}}
    </body>
</html>

bladeの方はおまけ的な感じですが、一応念のため。

1
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
1
0