Laravel Validation

フォームリクエスト

生成コマンド

php artisan make:request TestRequest

Validation

namespace App\Http\Requests;

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

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

 public function rules()
 {
  return [
   'column1' => 'required | array',
   'column2' => 'required | integer',
  ];
 }

 public function messages()
 {
  return [];
 }

 public function attributes()
 {
  return [
   'column1' => '〜',
   'column2' => '〜',
  ];
 }
}

使用

namespace App\Http\Controllers;

use App\Http\Requests\TestRequest;

class TestController extends Controller
{
 public function test(TestRequest $request)
 {
  〜
 }
}

バリデータ

Validation

namespace App\Rules;

use Illuminate\Support\Facades\Validator;

trait TestValidation
{
 protected function checkTest(Request $request)
 {
  $validator = Validator::make($request->all(),
   [
    'column' => ['max:255'],
   ],
   [
    'column.max' => 'E999',
   ]
  );
  
  失敗時
  if ($validator->fails()) {
   エラーコード取得
   $codes = $validator->errors()->all(); 
   
   return $codes;
  }

  成功時
  return true;
 }
}

使用

class TestController extends Controller
{
 use \App\Rules\TestValidation;

 public function test(Request $request)
 {
  $result = $this->checkTest($request);
 }
}

Follow me!

前の記事

Laravel 組込関数