Laravelで複数選択可能なチェックボックスを実装する

Laravel

Laravelで複数選択可能なチェックボックスを実装するためのベストプラクティスをご紹介します。これを読めば、もうチェックボックスの実装に悩む必要はありません。

モデル構造

例えば、User モデルに以下のようなリレーションを定義してみましょう。ユーザーには「作成者(Author)」と「編集者(Editor)」といった複数の役割を割り当てることができます。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class User extends Model
{
    /**
     * ユーザーに属するロール
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }
}

ルート定義

routes/web.phpファイルに以下のルートを定義してあるとしましょう。

use App\Http\Controllers\UserController;

Route::get('/users/{user}', [UserController::class, 'edit'])->name('user.edit');
Route::put('/users/{user}', [UserController::class, 'update'])->name('user.update');

GETのルートはユーザーの役割を編集するフォームを表示し、PUTルートで変更内容をデータベースへ保存します。

コントローラ実装

次に、これらのルートへの受信リクエストを処理するコントローラを見てみましょう。editメソッドではデータベースからすべての役割を取得してビューへ渡しています。

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * ユーザー編集画面の表示
     */
    public function edit(User $user)
    {
        $roles = Role::all();

        return view('user.edit', ['user' => $user, 'roles' => $roles]);
    }

    /**
     * ユーザー情報の更新
     */
    public function update(Request $request, User $user)
    {
        $request->validate(['roles' => 'array|exists:roles,id']);

        $user->roles()->sync($request->roles);

        return redirect()->route('user.edit', ['user' => $user]);
    }
}

チェックボックス表示

ビューでは渡された役割データをループ処理してチェックボックスを表示できます。今のところ、checked属性は設定していません。

<!-- /resources/views/user/edit.blade.php -->

<form action="{{ route('user.update', ['user' => $user]) }}" method="POST">
    @csrf
    @method('PUT')

    @foreach ($roles as $role)
        <div class="form-check">

            <input
                id="role{{ $role->id }}"
                type="checkbox"
                name="roles[]"
                @class(['form-check-input', 'is-invalid' => $errors->has('roles')])
                value="{{ $role->id }}"
            >

            <label for="role{{ $role->id }}" class="form-check-label">
                {{ $role->name }}
            </label>

            @if ($loop->last && $errors->has('roles'))
                <div class="invalid-feedback">{{ $errors->first('roles') }}</div>
            @endif

        </div>
    @endforeach

    <button class="btn btn-primary">保存</button>
</form>

チェック済み属性

それでは、checked属性を設定してみましょう。チェック済みの判定結果を、ビューへ渡すデータに付け足すようにします。

/**
 * ユーザー編集画面の表示
 */
public function edit(Request $request, User $user)
{
    $roles = Role::all()->keyBy('id')->toArray();
    foreach (array_keys($roles) as $role_id) {
        $roles[$role_id]['checked'] = false;
    }
    foreach ($request->old('roles', $user->roles->modelKeys()) as $role_id) {
        if (isset($roles[$role_id]['checked'])) {
            $roles[$role_id]['checked'] = true;
        }
    }
    return view('user.edit', ['user' => $user, 'roles' => $roles]);
}

これで、ビューでは渡されたデータのフラグを確認するだけでcheckedの判別ができるようになりました。

<!-- /resources/views/user/edit.blade.php -->

<form action="{{ route('user.update', ['user' => $user]) }}" method="POST">
    @csrf
    @method('PUT')

    @foreach ($roles as $role)
        <div class="form-check">

            <input
                id="role{{ $role['id'] }}"
                type="checkbox"
                name="roles[]"
                @class(['form-check-input', 'is-invalid' => $errors->has('roles')])
                value="{{ $role['id'] }}"
                @checked($role['checked'])
            >

            <label for="role{{ $role['id'] }}" class="form-check-label">
                {{ $role['name'] }}
            </label>

            @if ($loop->last && $errors->has('roles'))
                <div class="invalid-feedback">{{ $errors->first('roles') }}</div>
            @endif

        </div>
    @endforeach

    <button class="btn btn-primary">保存</button>
</form>

めでたし、めでたし☺

Laravelでのルーティングからビューにデータを渡すまで

Laravel

Laravelにおけるルーティングからビューにデータを渡すまでの基本的な実装パターンをまとめました。状況に応じて適切なパターンを使い分けましょう。

ルーティング

クロージャによるルーティングはいたって単純です。

Route::get('/', function () {
    return view('welcome');
});

ルーティングにクロージャを使用すると、ルートキャッシュは動作しません。ルートキャッシュを使用するには、コントローラルートを定義します。

Route::get('/user', 'UserController@index');

ビュールート

ルートからビューを返すだけの場合は、Route::viewメソッドを使用します。このメソッドを使用しても、ルートキャッシュは動作するようです。

Route::view('/welcome', 'welcome');

ビューにデータを渡す

viewヘルパ関数を使用して、データを配列でビューに渡せます。

Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});

withメソッドでビューに渡すデータを個別に追加することもできます。

Route::get('/', function () {
    return view('greeting')->with('name', 'Victoria');
});

ビュールートでデータを渡す

Route::viewメソッドでは、ビューへ渡すデータの配列を第3引数として指定します。

Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

ここで、allgetのようなメソッドでモデルを取得して渡すのは避けるべきです。モデルはクロージャやコントローラの中で取得しないと、該当ルート以外のリクエストでも、routes/web.phpファイルが読み込まれる毎にクエリが実行されてしまいます。また、場合によってはユニットテストでIlluminate\Database\QueryException例外が投げられることがあります。

Route::view('/', 'welcome', ['categories' => Category::all()]);
1) Tests\Feature\ExampleTest::testBasicTest
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: categories (SQL: select * from "categories")

これはテスト実行時、マイグレーションが実行される前に、routes/web.phpファイルが読み込まれることが原因です。

全ビュー間のデータ共有

アプリケーションの全ビューでデータを共有するには、View::shareメソッドを使います。

View::share('key', 'value');

通常、サービスプロバイダのbootメソッド内で呼び出しますが、ここでもモデルを取得して渡していると、先ほどの例と同様にエラーの原因になります。

参考
QueryException: General error: 1 no such table: {table_name} (SQL: select * from “{table_name}”) · Issue #27018 · laravel/framework

ビューコンポーザ

ビューコンポーザは、ビューがレンダーされる直前に呼び出されます。したがって、ビューにモデルを渡す場合にも使えます。

View::composer('welcome', function ($view) {
    $categories = Category::all();
    $view->with('categories', $categories);
});

ビューコンポーザを複数のビューに適用するには、View::composerメソッドの最初の引数を配列で渡します。

View::composer(['welcome', 'home'], function ($view) {
    //
});

composerメソッドに渡しているビュー名には、ワイルドカードとして*を使用することもできます。

View::composer('*', function ($view) {
    //
});

Laravelにおける存在チェックの書き方

Laravel

Laravelでビューに渡されたEloquentコレクションの中身が存在しているか判別するプログラムの書き方をまとめます。

データをビューへ渡す

まず、データを表示するためにEloquentでコレクションを取得してビューへ渡します。

public function index()
{
    $users = User::all();

    return view('users', ['users' => $users]);
}

単にデータを表示する

ビューに渡されたデータはループで表示できます。

<html>
    <body>
        <h1>User</h1>

        @foreach($users as $user)
            <p>{{ $user->name }}</p>
        @endforeach
    </body>
</html>

データの存在を判別する

データの存在を判別するには、isNotEmptyメソッドを使います。

<html>
    <body>
        <h1>User</h1>

        @if ($users->isNotEmpty())
            <ul>
                @foreach($users as $user)
                    <li>{{ $user->name }}</li>
                @endforeach
            </ul>
        @else
            Nothing Found
        @endif
    </body>
</html>

逆の動作である、isEmptyメソッドを使うこともできます。

<html>
    <body>
        <h1>User</h1>

        @if ($users->isEmpty())
            Nothing Found
        @else
            <ul>
                @foreach($users as $user)
                    <li>{{ $user->name }}</li>
                @endforeach
            </ul>
        @endif
    </body>
</html>

その他の判別方法

より単純なケースでは、@forelse()が使えるかもしれません。

<html>
    <body>
        <h1>User</h1>

        @forelse($users as $user)
            <p>{{ $user->name }}</p>
        @empty
            Nothing Found
        @endforelse
    </body>
</html>

ちなみに、以下のような書き方では@empty()がうまく判別できませんでした。

<html>
    <body>
        <h1>User</h1>

        @foreach($users as $user)
            <p>{{ $user->name }}</p>
        @endforeach
        @empty($users)
            Nothing Found
        @endempty
    </body>
</html>

リレーションの存在の判定

リレーションの有無を調べるには、existsメソッドとdoesntExistメソッドが使用できます。

<html>
    <body>
        <h1>User</h1>

        @if ($user->posts()->exists())
            The user has some posts
        @endif

        @if ($user->posts()->doesntExist())
            The user doesn't have any posts
        @endif
    </body>
</html>