Pattern suggestion for Requests

Posted 1 year ago by itstrueimryan

So I have separate create and update validation for each set of CRUD features on my site. These usually share a lot of common validation, but update may have like one more rule or a slightly different rule here or there. So I'm trying to come up with a way to avoid duplication and maintain SRP. Instead of having completely different files for updating and creating a particular something, I was doing something like:

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                'string',

and then I would have two files that inherit from this: CreateUser and UpdateUser, e.g.:

class CreateUser extends UserRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = parent::rules();

        $rules['username'][] = new MustBeUniqueWithinOrganization(User::class);

    return $rules;
     }

}

The problem is, now I have to call parent::rules() (or set this in the constructor) of every child request class, and that seems like too much duplication as well. I'm struggling to think of a good pattern to use here. Any suggestions are appreciated.

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.