Laravelで配列のパラメータをPOSTしたときのバリデーションの方法をお伝えしますね。
バリデーションはいくつかパターンがあると思うので、それぞれ参考コードを見せておきます。
Laravelで配列のPOSTパラメータのバリデーションをする方法
僕が一番使うFormRequestクラスを使う場合。
https://laravel.com/api/9.x/Illuminate/Foundation/Http/FormRequest.html
FormRequestクラスを使う場合
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreProjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'project.name' => 'required|string|max:80',
'project.website_url' => 'required|url|unique:projects,website_url',
'campaign.name' => 'required|string|max:80',
'campaign.type' => 'required|string|in:0,1',
];
}
}
rulesメソッドでreturnする配列をこのようにします。配列のキーをドットで繋ぎます。
これはこのようなPOSTパラメータを想定したバリデーションです。
$request = [
'project' => [
'name' => 'プロジェクト名',
'website_url' => 'https://website.com'
],
'campaign' => [
'name' => '年末セール',
'type' => 0
]
]
見たまんまだと思いますが、配列のキーをドットでつなぐだけです。
$request[‘project’][‘name’]なら ‘project.name’にするだけ。
簡単ですね!
Validatorファサードを使う場合
cotroller内でValidatorファサードを使う場合にはmakeメソッドでReuqestクラスのallメソッドで取得できるパラメータに対してバリデーションします。
https://laravel.com/api/9.x/Illuminate/Support/Facades/Validator.html#method_make
# controller
Validator::make($request->all(), [
'project.name' => 'required|string|max:80',
'project.website_url' => 'required|url|unique:projects,website_url',
'campaign.name' => 'required|string|max:80',
'campaign.type' => 'required|string|in:0,1',
]);
Requestクラスのvalidateメソッドを使う場合
次もコントローラ内でvalidateメソッド使う場合。
https://laravel.com/api/9.x/Illuminate/Http/Request.html#method_validate
# controller
$request->validate($request->all(), [
'project.name' => 'required|string|max:80',
'project.website_url' => 'required|url|unique:projects,website_url',
'campaign.name' => 'required|string|max:80',
'campaign.type' => 'required|string|in:0,1',
]);
ですね。
どの方法でもPOSTパラメータの多重配列のキーをドットでつなぐのは同じです。
一度覚えてしまえば簡単ですね!