I
I
ildar-meyker2019-11-23 14:45:29
Laravel
ildar-meyker, 2019-11-23 14:45:29

How to avoid code duplication when validating data in store and update methods?

If the validation logic were absolutely identical, it would seem that everything is simple. Can be moved to the rules and FormRequest method. But what if the check is slightly different?
store:

request()->validate([
            'name' => 'required',
            'poster' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
            'name_en' => [
                'required',
                Rule::unique('authors', 'name_en'),
                new AuthorUrl
            ]
        ]);

update:
request()->validate([
            'name' => 'required',
            'poster' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
            'name_en' => [
                'required',
                Rule::unique('authors', 'name_en')->ignore($author->id),
                new AuthorUrl
            ]
        ]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2019-11-23
@ildar-meyker

In the method rules(), you can adjust the list of rules depending on some conditions - the same http verb.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question