LoginSignup
0
0

More than 3 years have passed since last update.

都道府県名をセレクトボックスで使用したい時に、Configファサードを使ってみる。

Last updated at Posted at 2020-04-12

セレクトボックスを使用したい時に、optionタグを使う方法が思い浮かぶと思いますが、ビュー側のbladeに書くのが憚れるほど要素が多い時、例えば都道府県のように47個も書いてしまうと、それだけでbladeが散らかってしまいます。

そこで、こういったあらかじめ値や文字が決まっている場合は、別の場所にファイルを作って管理する方が便利です。

本記事では、Configファサードを使って呼び出す方法を紹介します。

都道府県のような固定値は、config内でファイルを作って管理しよう

まず、config配下にconstant.phpというファイルを作ります。

config.png

次に、constant.phpでは、都道府県の情報を書き込んでいきます。

return [
   '1' => '北海道',
   '2' => '青森',
   '3' => '岩手',
];

呼び出すときはConfigファサードで

まず、Configファサードを使用する宣言をします。

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Config; //Configファサードの宣言

あとは、使用したいところで呼び出すだけです。

public function post()
    {
      //これでconstant.phpで設定した値が使用できます
      $prefecture = Config::get('constant');

      return $prefecture;
    }

ちなみに、返り値は下記の通り、配列です。

array:3 [▼
  1 => "北海道"
  2 => "青森"
  3 => "岩手"
]
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