php - Laravel 5 validation in model
638
I have model like this
class test extends Model
{
public $rules = [
'title' => 'required',
'name' => 'required',
];
protected $fillable = ['title','name'];
}
And controller like this
public function store(Request $request)
{
$test=new test; /// create model object
$validator = Validator::make($request->all(), [
$test->rules
]);
if ($validator->fails()) {
return view('test')->withErrors($validator)
}
test::create($request->all());
}
Validation show error like this
The 0 field is required.
I want show this
The name field is required.
The title field is required.
Answer
Solution:
I solve it
Answer
Solution:
You are doing it the wrong way. The
rules
array should either be in your controller or better in a Form Request.Let me show you a better approach:
Create a new Form Request file with
php artisan make:request TestRequest
.Example
TestRequest
class:Inject the request object into your controller method.
Answer
Solution:
You could also look at validating in your model and throwing a ValidationException which will be handled as usual in your controller (with the error bag etc). E.g:
Then in my Controller:
Finally in my base service class
If the model validates it continues as usual. If there's a validation error it goes back to the previous page with the validation errors in the flash data/error bag.
I will most probably move the $person->validate() method to my service class, however it will still work as outlined above.
Answer
Solution:
You can simply make your validation by writing in Model.
In your Model File
i.e. Models\Test.php
In Controller
Just do this. Everything will be fine.