配列形式のデータをLaravelのValidatorで扱う方法

ありがちな処理の割に日本語の情報が無かったので若干苦労しました。
複数のスケジュールを入力するページをサンプルに作ってみました。

まず、スケジュールの入力画面とPOSTされた際に処理されるページを作ります。
routes.php
[php]
Route::get(‘/schedule’, [
‘as’ => ‘schedule’,
‘uses’ => ‘ScheduleController@index’,
]);
Route::post(‘/schedule’, [
‘as’ => ‘schedule_update’,
‘uses’ => ‘ScheduleController@update’,
]);[/php]

Class名はtwitter bootstrapの物なので無視してください。
色々試したのですが「weekday[]」の形式はwithInputが正常に動作しないので「weekday[$ii]」としました。
schedule.blade.php
[html]
@for($ii=0; $ii<10; ++$ii)

@endfor
[/html]

ScheduleController
[php]
public function index()
{
// 曜日の一覧
$weekday = [‘日’, ‘月’, ‘火’, ‘水’, ‘木’, ‘金’, ‘土’];

return View::make(‘schedule’, [
‘weekday’ => $weekday,
]);
}

public function update()
{
// バリデーションルール策定
$validation_rule = [
‘user_id’ => ‘required|integer’,
];

// $validation_ruleのKeyをドットで表した配列形式にするのがポイント
foreach (Input::get(‘weekday’) as $key => $value) {
$validation_rule[‘weekday.’ . $key] = ‘integer’;
}
foreach (Input::get(‘start’) as $key => $value) {
$validation_rule[‘start.’ . $key] = “required_with:end.” . $key;
// バリデーションのエラーメッセージもここで生成しておきます。
$messages[‘start.’ . $key . ‘.required_with’] = ‘「始め」を指定する場合は「終わり」も指定して下さい。’;
}
foreach (Input::get(‘end’) as $key => $value) {
$validation_rule[‘end.’ . $key] = “required_with:start.” . $key;
$messages[‘end.’ . $key . ‘.required_with’] = ‘「終わり」を指定する場合は「始め」も指定して下さい。’;
}

$validator = Validator::make(Input::all(), $validation_rule, $messages);

if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
}[/php]

Laravelエキスパート養成読本 [モダンな開発を実現するPHPフレームワーク!]

スポンサーリンク
レクタングル大