Fayakon
Fayakon

Reputation: 1523

Data validation in Laravel is not working

I've created a custom request in my project, but somehow it is not working. I'm facing two errors. I'm trying to show a message on view if validation fails through Ajax.

1) 422 Unprocessable Entity error

and

2) Undefined variable: teacherrequest

validation rules which i set in Request folder,

TeacherRequest.php:

public function rules()
{
    return [
        'Name' => 'required|regex:/^[\pL\s\-]+$/u',
        'FName' => 'required|regex:/^[\pL\s\-]+$/u',
    ];
}

Controller:

public function update(TeacherRequest $request, $id)
{
    if ($teacherrequest->fails()) {
        return response()->json([
            'msg' => 'Please Enter Correct Data',
        ]);
    }
}

AJAX:

success: function (data) {

if(data.msg){
        alert("please validate data");

}
}

Update:

if i remove if condition, i am getting 422 error, how to show that on view?

Upvotes: 1

Views: 774

Answers (3)

Jrb
Jrb

Reputation: 461

First, public function update(TeacherRequest $request) so in the function you need to use $request not $teacherrequest.

And second You need to have public function authorize() returning true.

Upvotes: 2

brice
brice

Reputation: 1881

If you type hint your request class as a parameter in your controller's action method (like you are doing in the example above) Laravel will automatically run your validation rules and return a 422 Unprocessable Entity if validation fails. You don't need to manually check if validation fails like you're doing above; in your controller's update method you can just implement the logic you want to run when validation passes.

Also on your front end you will need to use the error ajax callback to display the error message because a 422 status code is not considered successful.

See the documentation on creating form requests.

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.

Upvotes: 0

Ghiffari Assamar
Ghiffari Assamar

Reputation: 661

You define TeacherRequest as $request TeacherRequest $request

but in next line use it as

if ($teacherrequest->fails()){ // this is wrong

correct one should be define like this

TeacherRequest $teacherrequest

or if you didn't change the dependency injection, just change the validator like this

if ($request->fails()){

summary: why error happened already specifically explained which is undefined teacherrequest variable, therefore 2 solutions above can solve it

Upvotes: 0

Related Questions