目次

【Laravel】requiredIf を使って新規登録の場合のみ必須チェックを行う

新規登録時のみ、パスワードを必須とする例。

routes\web.php

Route::prefix('user')->name('user.')->group(function(){
    Route::get('', 'UserController@index')->name('home');
    Route::get('create', 'UserController@create')->name('create');
    Route::get('{user}/edit', 'UserController@edit')->name('edit');
    Route::post('{user?}', 'UserController@store')->name('store');
});

App\Http\Controllers\UserController

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

# models
use App\Models\User;

# requests
use App\Http\Requests\UserRequest;

class UserController extends Controller
{
    public function store(User $user, UserRequest $request)
    {
        if (is_null($user->id)) {
            $user = new User();
        }

        $user->fill($request->all());

        // パスワードの入力があった場合のみ暗号化して保存
        if (!is_null($request->password)
            && strlen($request->password) > 0
        ) {
            $user->password = bcrypt($request->password);
        }

        $user->save();

        return redirect(route('user.home'));
    }
}

App\Http\Requests\UserRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name'                  => 'bail|required|max:100',
            'email'                 => 'bail|required|max:255|email:strict',
            'password'              => [
                'bail',
                // $this->user が null ならば必須
                Rule::requiredIf(is_null($this->user ?? false)),
                'between:8,32',
            ],
        ];
    }

    public function prepareForValidation()
    {
        // 「全角」英数字を「半角」に変換
        $this->merge(['email' => mb_convert_kana($this->email, 'a')]);
        $this->merge(['password' => mb_convert_kana($this->password, 'a')]);
    }

    public function attributes()
    {
        return [
            'name'                  => '名前',
            'email'                 => 'メールアドレス',
            'password'              => 'パスワード',
        ];
    }
}