LoginSignup
1
1

More than 3 years have passed since last update.

Laravelでユーザーごとにセレクトボックスの内容を変える

Posted at

ユーザーごとに選択肢が変わるセレクトボックスを作ったので、そのメモとして。

前提

バージョン:Laravel6
データベース構成:usersとitemsをuser_idで紐づけ

users
id|name
items
id|user_id|name

データベースの中身は冗長なのでページ下部に記載

実装方法

①選択肢の抽出

controller側でログイン中のuserのidを取得して、選択肢を抽出する。
sellectionsには連想配列でitemのidとnameを紐づけておく。
抽出条件を変えればより複雑な条件分岐もできそう。

SelectboxController.php
public function selectbox() {
    // ログイン中のユーザーを取得
    // findOrFail使用のためゲストや存在しないidの場合は404エラー
    $user = User::findOrFail(\Auth::id());

    // user_idでitemを抽出
    $items = Item::where('user_id', $user->id)->get();
    // 抽出したitemから選択肢を作成
    $selections = [];
    foreach($items as $item) {
        $selections[$item->id] = $item->name;
    }

    // viewを出力
    return view('selectbox',[
        'user' => $user,
        'selections' => $selections
    ]);
}
selectbox.blade.php
<p>{{ $user->name }}としてログイン</p>

// Laravel collectiveを使う場合
{!! Form::open(['route' => 'selectboxResult', 'method' => 'post']) !!}
    {!! Form::label('selection', '選択肢') !!}
    {!! Form::select('selection', $selections) !!}
    {!! Form::submit('送信') !!}
{!! Form::close() !!}

// パッケージを使わない場合
<form method="post" action="{{ route('selectboxResult') }}" accept-charset="UTF-8">
    {{ csrf_field() }}
    <label for="selection">選択肢</label>
    <select id="selection" name="selection">
        @foreach($selections as $itemId => $itemName)
            <option value="{{ $itemId }}">{{ $itemName }}</option>
        @endforeach
    </select>        
    <input type="submit" value="送信">
</form>
web.php
Route::get('/selectbox', 'SelectboxController@selectbox')->name('selectbox');

②送信結果の表示

optionタグでitemのidを送信しているので、controllerでidから抽出する。

SelectboxController.php
public function selectboxResult(Request $request) {
    // idからitemを抽出
    $item = Item::findOrFail($request->selection);

    //viewを出力
    return view('selectboxResult',[
        'item' => $item
    ]);
}
```html:selectboxResult.blade.php
<p>idは{{ $item->id }}</p>
<p>名称は{{ $item->name }}</p>
web.php
Route::post('/selectbox/result', 'SelectboxController@selectboxResult')->name('selectboxResult');

③実行結果

user1でログインしている場合
user1.gif
user7でログインしている場合
user7.gif

サンプルコード全文

SelectBoxController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Item;

class SelectboxController extends Controller
{
public function selectbox() {
    // ログイン中のユーザーを取得
    // findOrFail使用のためゲストや存在しないidの場合は404エラー
    $user = User::findOrFail(\Auth::id());

    // user_idでitemを抽出
    $items = Item::where('user_id', $user->id)->get();
    // 抽出したitemから選択肢を作成
    $selections = [];
    foreach($items as $item) {
        $selections[$item->id] = $item->name;
    }

    // viewを出力
    return view('selectbox',[
        'user' => $user,
        'selections' => $selections
    ]);
}

    public function selectboxResult(Request $request) {
        // idからitemを抽出
        $item = Item::findOrFail($request->selection);

        //viewを出力
        return view('selectboxResult',[
            'item' => $item
        ]);
    }
}
selectbox.blade.php
<!DOCTYPE html>

<html lang="ja">

<head>
    <meta charset="utf-8">
    <title>selectbox</title>
</html>

<body>

    <p>{{ $user->name }}としてログイン</p>

    {!! Form::open(['route' => 'selectboxResult', 'method' => 'post']) !!}
        {!! Form::label('selection', '選択肢') !!}
        {!! Form::select('selection', $selections) !!}
        {!! Form::submit('送信') !!}
    {!! Form::close() !!}

    <form method="post" action="{{ route('selectboxResult') }}" accept-charset="UTF-8">
        {{ csrf_field() }}
        <label for="selection">選択肢</label>
        <select id="selection" name="selection">
            @foreach($selections as $itemId => $itemName)
                <option value="{{ $itemId }}">{{ $itemName }}</option>
            @endforeach
        </select>        
        <input type="submit" value="送信">
    </form>

</body>

</html>
selectboxResult.blade.php
<!DOCTYPE html>

<html lang="ja">

<head>
    <meta charset="utf-8">
    <title>selectboxResult</title>
</html>

<body>

    <p>idは{{ $item->id }}</p>
    <p>名称は{{ $item->name }}</p>

</body>

</html>
web.php
<?php
Route::get('/selectbox', 'SelectboxController@selectbox')->name('selectbox');
Route::post('/selectbox/result', 'SelectboxController@selectboxResult')->name('selectboxResult');

データベースの中身

users
SELECT * FROM users;
id|name
1|user1
2|user2
3|user3
4|user4
5|user5
6|user6
7|user7
8|user8
9|user9
10|user10
items
SELECT * FROM items;
id|user_id|name
1|9|item1
2|2|item2
3|6|item3
4|4|item4
5|6|item5
6|9|item6
7|8|item7
8|1|item8
9|3|item9
10|5|item10
11|1|item11
12|9|item12
13|10|item13
14|4|item14
15|2|item15
16|7|item16
17|7|item17
18|10|item18
19|3|item19
20|10|item20
21|2|item21
22|9|item22
23|7|item23
24|2|item24
25|4|item25
26|1|item26
27|5|item27
28|2|item28
29|4|item29
30|3|item30
1
1
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
1