例えば、メンバー登録時に’年’, ‘月’, ‘日’とpostされる生年月日を有効な日付かをチェックする場合
MemberRequest.php
<?php
namespace App\Http\Requests\User;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\User\BirthdayRule; // BirthdayRuleを使うことを宣言
class MemberRequest extends FormRequest
{
private $birth_y;
private $birth_m;
private $birth_d;
public function authorize()
{
return true;
}
public function all($keys = null)
{
$results = parent::all($keys);
// '年','月','日'をプライベート変数に退避
$this->birth_y = $results['birth_y'] ?? null;
$this->birth_m = $results['birth_m'] ?? null;
$this->birth_d = $results['birth_d'] ?? null;
return $results;
}
public function rules()
{
return [
'birth_y' => [
'required',
'max:4',
new BirthdayRule(
$this->birth_y,
$this->birth_m,
$this->birth_d,
)
],
'birth_m' => 'required|alpha_num|max:2',
'birth_d' => 'required|alpha_num|max:2',
];
}
public function attributes(){
return [
'birth_y' => '生年月日(年)',
'birth_m' => '生年月日(月)',
'birth_d' => '生年月日(日)',
];
}
}
BirthdayRule.php
<?php
namespace App\Rules\User;
use Illuminate\Contracts\Validation\Rule;
class BirthdayRule implements Rule
{
private $birth_y;
private $birth_m;
private $birth_d;
public function __construct($birth_y, $birth_m, $birth_d)
{
$this->birth_y = $birth_y;
$this->birth_m = $birth_m;
$this->birth_d = $birth_d;
}
public function passes($attribute, $value)
{
return checkdate(
(int)$this->birth_m,
(int)$this->birth_d,
(int)$this->birth_y
);
}
public function message()
{
return '誕生日は、有効な日付を指定して下さい。';
}
}