A
A
Andrey Boychenko2016-04-29 11:17:53
JavaScript
Andrey Boychenko, 2016-04-29 11:17:53

Return ajax validation from request Laravel 5?

Good afternoon! Weak with JS and not very strong with laravel (

At first I did such a "validation", but is it bad form?

$extention = $request->file('file')->getClientOriginalExtension();


        if( $extention == 'jpg' or $extention == 'jpeg' or $extention == 'png' or $extention == 'rar' )
        {
            $name = $request->file('file')->getClientOriginalName();
            $img = $name .".".$extention;
            if( $request->file('file')->move( base_path() . '/public/images/catalog/', $img ) )
            {
                $status = true;
            }
        }
        else{
            $status = false;
        }
        return response()->json([ "STATUS" => $status ]);

Using this approach, I receive a JSON response and display the desired message to the client. But I want to use the "correct" validation. that's why I wrote it like this - php artisan make: request RequestName and in general I wrote it there
public function rules()
    {
        return [
            //
            'file' => 'required|mimes:jpg,png,mp4,webm',
        ];
    }

And here it is not clear to me how to return the validation result in the form of JSON for its subsequent processing? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2016-06-27
@Result007

Hey! Try this option :)

// Правила можешь вынести в функцию в модели
$rules = [
    'file' => 'required|mimes:jpg,png,mp4,webm',
];

$validation = Validator::make($request->all(), $rules);
if( $validation->fails() ) {
    $errors = $validation->messages()->toJson();
}

return response()->json([ "errors" => $errors ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question