Laravel Model バリデーション実装

Larave、ModelのSave時にバリデーションを実装


バリデーションの実装

\app\ValidateOnSave.phpを作成。

\app\ValidateOnSave.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
 
namespace App;
 
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
 
trait ValidateOnSave
{
    protected function rules():array
    {
        return [];
    }
 
    public function save(array $options = [])
    {
        $rules = $this->rules();
        if (count($rules)) {
            $subject   = $this->attributes;
            $validator = Validator::make($subject, $rules);
 
            if ($validator->fails()) {
                throw new ValidationException($validator);
            }
        }
        return parent::save($options);
    }
}

Model\app\Sample.phpを作成しバリデーションを実装。

\app\Sample.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
namespace App;
 
class Sample extends Model
    use ValidateOnSave;
 
    // バリデーションルールの記載
    protected function rules(){
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ];
  }
}

実際にSampleクラスのsaveを実行してバリデーションを出してみます。。

実行
1
2
$sample = new Sample();
$sample->save();  // バリデーションが実行されてエラーが出される

これでValidationExceptionがthrowされます。


参考

0 件のコメント :

コメントを投稿