カスタマイズ前
フォームリクエストをartisan makeで作成すると、
$ php artisan make:request StoreBlogPost
以下のように作成されます。
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreBlogPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
エラー時メッセージを変更できるmessages()や、属性名を変更できるattributes()を自分はよく設定します(オーバーライドします)が、最初は記載されていません。
これは以下の方法で自分好みにできます。
カスタマイズする
手順は以下です。
- コマンドを作る
- スタブファイルを作る
1. コマンドを作る
まずはartisan make:commandでコマンドを作成します。app/Console/Command
下に作成されます。
$ php artisan make:command CustomRequestMakeCommand
artisan make:requestはIlluminate/Foundation/Console/RequestMakeCommand
で実装されてますから、継承しちゃいます。
name, description, getStub()をオーバーライドしましょう。
<?php
namespace App\Console\Commands;
use Illuminate\Foundation\Console\RequestMakeCommand;
class CustomRequestMakeCommand extends RequestMakeCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:custom-request';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new custom form request class';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/custom-request.stub';
}
}
2. スタブを作る
getStub()で指定したapp/Console/Commands/stubs/custom-request.stub
を作成します。
Illuminate/Foundation/Console/stubs/request.stub
を元にmessages(), attiributes()を追記します。
ついでにバリデーション失敗時のリダイレクト先を指定できるredirectRouteも追記し、authorize()の戻り値をtrueにしておきました。
<?php
namespace DummyNamespace;
use Illuminate\Foundation\Http\FormRequest;
class DummyClass extends FormRequest
{
/**
* The route to redirect to if validation fails.
*
* @var string
*/
protected $redirectRoute;
/**
* 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
*/
public function rules()
{
return [
//
];
}
/**
* Get custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return [
//
];
}
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function attributes()
{
return [
//
];
}
}
確認
# 最初に作ったStoreBlogPostを削除してから
$ php artisan make:custom-request StoreBlogPost
custom-request.stubの内容で作成されるようになりました。