Laravel Form Request: Store/Update - Same or Separate Class?

Поделиться
HTML-код
  • Опубликовано: 8 фев 2025
  • Let's dive into some examples of how/when you would use the same or separate Form Request classes for validation. Spoiler alert: it's mostly a personal preference.
    - - - -
    Support the channel by checking out our products:
    Enroll in my Laravel courses: laraveldaily.t...
    Try our Laravel QuickAdminPanel: bit.ly/quickad...
    Purchase my Livewire Kit: livewirekit.com
    View Laravel Code Examples: laravelexample...
    Subscribe to my weekly newsletter: bit.ly/laravel-...

Комментарии • 93

  • @intipontt7490
    @intipontt7490 3 года назад +21

    I prefer the first approach (separate store and update, even if there's redundancy).
    If you want to use a single request with unique validation, I think you can achieve this with the new null-safe operator introduced in php8 or with the optional() helper like so:
    'email' => [ 'required', Rule::unique( 'users' )->ignore( optional( $this )->admin )) ]

    • @LemarinelNet
      @LemarinelNet 2 года назад

      Sure, separate classes are best, even if code is duplicated at first.
      The authorize method seems the correct place to apply policy and gate, so it allows for cleaner code and avoid duplicating gates somewhere else !

    • @i_zoru
      @i_zoru Год назад

      this one somehow relate, i currently fixing a bug where the edit are bugged because it uses the same validator as the create request, where also include unique data such as ID, so every time i make a request the ID are detected as an input , and thinking it as a create request , so i have to come up with the solution where i make sure to detect the API method that are being used, if it's create /post then i will add several new rules for the request validation

  • @we5tbevryertyv
    @we5tbevryertyv 3 года назад +2

    A) I don't think you understand what Single Responsibility means. It does not mean one method per class, lol. If that is the definition, then your controller is violating it too ;)
    B) Removing the password field/property from the request defeats the whole point of using the 'sometimes' rule. Just don't use it, lol. If it's not 'required' (or 'sometimes') it can be present in the request, or not, or it can be present and set to null. This seems to be the functionality you're looking for on update. No extra/different rule necessary...unless I'm missing something.
    C) You look like Sergio Perez's father! Awesome! He's my favorite Formula 1 driver.
    D) Thanks for all the great videos!

  • @ward7576
    @ward7576 3 года назад +6

    Trying to make it as efficient as possible (with multiple conditionals) is just making it harder and harder to read. Do this instead: define validation rule sets for each route that hits that validator. For each route define the route name as the key to which the values are the validation array you would put normally. Then, by using this in a look-up table manner, you can easily provide the validation rule set you need (by passing in route name as a key to the look-up table of rule sets).
    Although there will be duplicates in rules, it does change 2 things - now the logic is more readable for multiple route support and rules are in one place, desatured of conditionals in order to make it as easily updateable as possible.
    Guys, look-up tables are damn powerful. Use them. Or match expression, it's powerful also.

    • @legato0
      @legato0 3 года назад +3

      Something like that ?
      $rules = [
      'POST' => [
      'password'' => ['required']
      ],
      'PATCH' => [
      'password' => ['optional']
      ]
      ];
      return array_key_exists($this->method(), $rules) ? $rules[$this->method()] : [];

    • @ward7576
      @ward7576 3 года назад +2

      @@legato0 Yeah. Or use route names for keys.

  • @GergelyCsermely
    @GergelyCsermely 3 года назад +2

    Thanks. Is very interesting to compare so many options. I prefer one Class with optional field with the new when methode it is mutch more easy

  • @tarekalhalabi8776
    @tarekalhalabi8776 3 года назад +1

    Woow, i didn't know that we can access the controller's variables inside the form request, this piece of information is very useful, thank you💙

  • @michaloravec14
    @michaloravec14 3 года назад +11

    Never call $this->admin->id, instead of that use $this->route('admin')->id, imagine you have input with the name "admin" then you have a problem.

  • @KnightYoshi
    @KnightYoshi 3 года назад +1

    Separate validators for store and update. Then you can easily apply different permission checks; such as can create, but not update.
    You could argue that you can use an if-statement here, but then you introduce more cognitive complexity, as developers have to understand the if-statement - for lesser experienced/junior developers this *could* be more tedious.
    It's just more straightforward IMO to separate them, plus for the cases you mentioned about having different fields

  • @phpcoding9282
    @phpcoding9282 3 года назад +18

    I would have to disagree at 3:32 - The validation should just be validating the data not deciding what data to validate based on the name of a route. The validation class shouldn't be concerned with routes. Single Responsibility?

  • @sefaut
    @sefaut 2 года назад

    Great, exactly what I searched!

  • @johwel340
    @johwel340 3 года назад

    Chief thank you for the dark theme as well.

  • @inso4606
    @inso4606 3 года назад +2

    I prefer to use one request for store and update (It is easy if controllers are 10 or 20, but if they are 200?). In most cases. But, insteat of checking request()->routeIs(...) I'm using $this->route('user') !== null (if is used Route model binding). This prevent for errors if we change the route for some reason (even the route is changed, url must contain {user}). And I have custom stub for those kind of request, where just throw model in artisan command. And I think $this->route('admin') is little better than $this->admin :)

  • @tamimikbal28
    @tamimikbal28 3 года назад +1

    I can use both, And I have used them in different project.
    As I follow you and you are my idle. I want to know that which one you have used. I will use that.
    Thank you sir😍

  • @alila3883
    @alila3883 3 года назад +1

    For me, I prefer the use one class with a method switch inside rules method:
    EX. switch ($this->method()) {
    case 'POST':
    {
    return [
    'password'' => ['required']
    ];
    }
    case 'PUT':
    case 'PATCH':
    {
    return [
    'password' => ['optional']
    ]
    }
    default: break;

  • @kwameadoko9542
    @kwameadoko9542 3 года назад

    I mostly put all requests into the same class say UserRequest and have the logic base of the request method with a switch case which cases are request methods. this->method() would return the request type if you follow good standards like a post to create, put to update, etc. Delete and Update always return an empty array are grouped. Put and patch are also grouped as they perform almost the same thing.
    Code below:
    $rules = [];
    switch($this->method()) {
    case ‘GET’:
    case ‘DELETE’: {
    return $rules;
    }
    case ‘POST’: {
    // rules here
    }
    case ‘PUT’:
    case ‘PATCH’: {
    // rules here
    }
    return $rules;
    }

  • @gamerneversleep4200
    @gamerneversleep4200 3 года назад +1

    i make 2 request for update and store. Thanks for sharing 🙂.

  • @OnlinePseudonym
    @OnlinePseudonym 3 года назад

    Not sure if it's mentioned, but I think that with the classes that share the same implementation, it seems reasonable to use separate classes, but have them both subclass from a common parent class so as to cut down on the duplication.

  • @debjit21
    @debjit21 3 года назад +1

    I have recently used UserRegistration Request for the same and just use the same rules for register and update. I just used $request->except('password') to not include the password then check make it has and add $data['password'] = $hasedPassword. This way I have written more readable code and made it simple for onboarding other dev easy.

    • @werty2172
      @werty2172 3 года назад +1

      Its easier to separate them. So you dont have to tell your team to do those except method and hashed password

    • @debjit21
      @debjit21 3 года назад

      @@werty2172 May be do when I refactor but for quick prototyping it is fine.

    • @werty2172
      @werty2172 3 года назад +1

      @@debjit21 its not

    • @debjit21
      @debjit21 3 года назад

      @@werty2172 Yes it is.

    • @werty2172
      @werty2172 3 года назад

      Okay. If u say so.

  • @ahmedrezwan3856
    @ahmedrezwan3856 3 года назад

    I personally like to use switch case on the basis of method for each different action.

  • @JamesAutoDude
    @JamesAutoDude 2 года назад +1

    Could always use a Service to call the same service under the store & update functions

  •  3 года назад +1

    I prefer to use the last method, I mean , the same request for the two methods I think it's more simple! But every option is valid

  • @TobiasOlssonHovby
    @TobiasOlssonHovby 3 года назад +2

    I create two classes, store and update. The update class extends the store class. This way the update class will be empty until the rules need to be different.

    • @ward7576
      @ward7576 3 года назад

      How is update class a child of store class in this hierarchy? Makes no sense. Tho it works.

    • @mabdullahsari
      @mabdullahsari 3 года назад

      Pretty sure the FormRequest won't be autovalidated if you do this.

  • @abdurroquib7051
    @abdurroquib7051 3 года назад

    If there is less conditions in the form requests class, this will be a best choice, otherwise two different class much more beneficial.

  • @michakoodziejczyk1848
    @michakoodziejczyk1848 3 года назад

    I use first approach, but if I have the same rules or similar I extend FormRequest one from another or from base one

  • @kostjantin
    @kostjantin 3 года назад

    I like the first example, but have one question
    What about the next apis? How to create one request class for them:
    POST /api/reservation/
    {
    reservation_id: string,
    request params ....
    }
    and
    PUT /api/reservation/[reservation_id]
    {
    request params ....
    }

  • @liteninkiran
    @liteninkiran 3 года назад

    Hi. I really like your videos. You discuss topics that are actually practical and useful! I am currently trying to find out how to access the validation errors. The docs say that they are flashed to the session, but I don't know how to access them.

    • @liteninkiran
      @liteninkiran 3 года назад

      It turns out I needed "Accept" and "application/json" in the request header.

  • @gabrielLlanesMX
    @gabrielLlanesMX 2 года назад

    Can I set a flash session message in FormRequest?

  • @Shez-dc3fn
    @Shez-dc3fn 3 года назад

    how do u reconcile the whole KISS with what may happen in future? theres a mantra that says dont worry about future? so if create/update are same now they shud be one Request, if there is a difference in 'future' (which may or may not happen) u can deal with it later

  • @David-po3li
    @David-po3li 3 года назад

    Is it possible to pass an id manually in the requests class when we use that requests class in the middle part of the controller?

  • @saranraj3708
    @saranraj3708 2 года назад

    What is two type of request in laravel?

  • @halzagh2891
    @halzagh2891 3 года назад

    thanks very interesting

  • @MrDragos360
    @MrDragos360 3 года назад

    What about using Auth::id() for getting the logged user id inside form request ? I use it and it works

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Yes, if you're editing your own user. But in this case, super-admin is editing ANOTHER user's profile.

  • @OnlinePseudonym
    @OnlinePseudonym 3 года назад +1

    Checking for the route name / method in the request classes seems like an anti-pattern to me. It entagles the request object, with the particular route or method that it may be used in - when I think it's better to keep those concerns separated.

    • @soniablanche5672
      @soniablanche5672 3 года назад +2

      I disagree, those are literally methods inside the Request class. If any class should be using them it's Request.

    •  3 года назад

      Anti-pattern? I don't think so. He's just using stuff from Illuminate\Foundation\Http\FormRequest. FormRequest is meant for nasty logic and help on keeping your controllers clean. I even use authorize() to check for subscriptions.

    • @OnlinePseudonym
      @OnlinePseudonym 3 года назад

      ​@@soniablanche5672 ​Good point... there's something about it I don't like though...it feels like that the request object ought to be abstracted from the name of the route that it may happen to be received on. Maybe it's not so bad - just not my first preference.

    • @OnlinePseudonym
      @OnlinePseudonym 3 года назад

      Good point - I'll have a rethink. I'm not a fan of this particular approach though - maybe I don't have a good reason though :-)

  • @thamibn
    @thamibn 3 года назад

    What if there's is no model route binding, how can you do the update with unique rule?

  • @oguz4158
    @oguz4158 3 года назад

    Hi Man, I can try image file upload with ajax to Laravel Controller, and with controller another project I wanna post that file for save to api but i can't do that, How can I write?

  • @imranlashari6578
    @imranlashari6578 3 года назад +1

    Different Store & Update with different requests

  • @arturkhachatryan63
    @arturkhachatryan63 3 года назад +1

    what theme do you use and font for phpstorm ? Thank you.

  • @bdsumon4u
    @bdsumon4u 2 года назад

    UpdateRequest extends StoreRequest

  • @gianfrancobriones
    @gianfrancobriones Год назад

    I need help. The Update Form Rquest Class, since it's the PUT-magic and model bound, how do I call the instance of that model inside the Update Request Class? Help.

  • @vovkko
    @vovkko 3 года назад

    As many requests as needed. First option

  • @somethingmysterious58
    @somethingmysterious58 2 года назад

    currently I am facing an issue.
    while updating a record in api, I need to skip unique check from current row..
    for example
    1- name:Dary
    2- name:Junaid
    if I update 2 with Junaid again it should be okay, but when I try to update Junaid on 1 it show throw duplicate name error.. how should I write my custom for request for that?

    • @LaravelDaily
      @LaravelDaily  2 года назад

      I've googled the docs for you.
      The docs: laravel.com/docs/9.x/validation#rule-unique
      Read the section "Forcing A Unique Rule To Ignore A Given ID:"

  • @bumblebity2902
    @bumblebity2902 3 года назад +2

    Using OOP extends magic, to inherit store class info and modify or use switch/case approach, usually what I've seen in Laravel forums.

    • @KnightYoshi
      @KnightYoshi 3 года назад +1

      This is also true; I've done this before. If you have common rules, but different permission checks, extend a base form validator class, you can then call the parent rules and add (or even remove) fields as needed

  • @NOWAY-jg2lf
    @NOWAY-jg2lf Год назад

    I know that maybe my question is not related to the video, but I would like to ask you a question.
    If I have a settings table for my site, and in this table I have added the maximum characters to username field for example.
    can i use the settings model in my form request validation like this..
    public function rules(): array
    {
    $maxUserName = Setting::where('key', 'max_username')->value('value');
    return [
    'name' => [
    'required',
    'string',
    'max:' . $maxUserName,
    'unique:users,name'
    ],
    }
    does it allowed or it is safe to use this way ?

    • @LaravelDaily
      @LaravelDaily  Год назад +1

      Should be working!

    • @NOWAY-jg2lf
      @NOWAY-jg2lf Год назад

      @@LaravelDaily Thank you, I was just worried if it might cause a security issue

  • @MahfuzurRahmanSaber
    @MahfuzurRahmanSaber 3 года назад

    While working with ajax how can i use form request ? I noticed $request->validated() doesn't work with ajax.

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Not sure, should be working, not sure why it doesn't work for you.

    • @MahfuzurRahmanSaber
      @MahfuzurRahmanSaber 3 года назад

      @@LaravelDaily may be i did something wrong. Still could not figure out. Even i could not find a solution in the internet. Everyone's doing it in the controller. Found no example for form request and ajax. 😕

  • @nabeelyousafpasha
    @nabeelyousafpasha 3 года назад +2

    I am genuinely in a favour to use same class in order to supplement DRY.
    However it depends on scenario, but I usually do something like below:
    public function rules()
    {
    $rules = [
    'registration_type_id' => ['required', 'numeric', "exists:".RegistrationType::class.',id',],
    'step_number' => [
    'required', 'numeric',
    Rule::unique('steps')->where(function ($query) {
    return $query->where('registration_type_id', '=', $this->registration_type_id);
    }),
    ],
    'name' => ['required', 'string',],
    'request_type_id' => ['required', 'numeric', "exists:".RequestType::class.',id',],
    ];
    switch($this->method())
    {
    case 'GET':
    case 'DELETE':
    {
    $rules = [];
    break;
    }
    case 'PATCH':
    case 'PUT':
    case 'POST':
    {
    break;
    }
    default:break;
    }
    return $rules;
    }
    Please share your thoughts @povilas @laravel-daily
    Respect from Pakistan.

    • @LaravelDaily
      @LaravelDaily  3 года назад +3

      Personally, that switch-case sounds too complicated for me, wouldn't it be possible to shorten it to if-else?

    •  3 года назад

      @Nabeel Yousaf Pasha Your solution is kinda ugly tho. You can create your own base FormRequest which extends Illuminate\Foundation\Http\FormRequest. There you declare 2 methods: isPost() => strtolower($this->method()) === 'post'; isEdit() => in_array(strtolower($this->method()), ['patch', 'put']);
      Note: short closure syntax won't work (yet) in your class. I used them here for algorithmic purpose.

  • @jemelo79
    @jemelo79 2 года назад

    Diferent, most of the times they are diferent, sometimes they start the same and end diferent, so I just make two

  • @amrosdn
    @amrosdn 3 года назад

    hi
    could you please tell me what's the difference between thus files and the below code in the controller :
    $validatedData = $request->validate([
    'am_txt1' => 'required',
    'am_txt2' => 'required',
    'am_txt3' => 'required',
    'am_txt4' => 'required',
    'am_txt5' => 'required',
    ]);
    best regards

    • @ShadiMuhammad
      @ShadiMuhammad 2 года назад

      As the SOLID principles state, "Every Class Should Have a Single Responsibility",
      means that the controllers role is to send and receive data agnostically without knowing its logic.
      So we separate the "Validation Logic" in a Separate Class and return the result to the Controller.
      ...
      You may search for: SOLID principles, Separation Of Concerns to know more.
      Keep It Up Bro 👏

    • @ShadiMuhammad
      @ShadiMuhammad 2 года назад

      Povilas has a short video too about the same topic
      ruclips.net/video/3P2uNeY9Azs/видео.html

  • @soniablanche5672
    @soniablanche5672 3 года назад

    any reason why you used request() instead of $this ? you're inside a Request class after all.

    • @LaravelDaily
      @LaravelDaily  3 года назад

      No reason, probably $this should work, too

  • @AARP41298
    @AARP41298 2 года назад

    7:03 im using only $id as the second parameter of update
    and using it in the Request as $this->id
    BUT it doesnt work
    I check how the id has renamed in the route list ex.
    api/user/{user}
    and then in the request now i use
    $this->user

  • @Realtek2super
    @Realtek2super 3 года назад

    Instead of $this->admin->id, I use auth()->id()

    • @LaravelDaily
      @LaravelDaily  3 года назад +1

      That's if you're updating your own record, right? But what if not?

    • @Realtek2super
      @Realtek2super 3 года назад

      @@LaravelDaily yes, only for updating.

    •  3 года назад +1

      @@Realtek2super Only if you want to ignore the currently logged in user.

  • @jijiwaiwai
    @jijiwaiwai 3 года назад +1

    I prefer to separate them which gives our maximum flexibility, you never know what weird requirements your client wants in the future 😂

  • @StefanKressCH
    @StefanKressCH 3 года назад +1

    Even though i can follow the argumentation of single responsibility, I would prefer one single class for the same model, if the structure would allow it. If I would follow the same idea by structuring the request classes in folders, I could as well follow the strategy to have only one method per controller, create multiple controllers, organize them in different folders and thus separate everything. That would end up too atomic....

  • @bdsumon4u
    @bdsumon4u 3 года назад

    First.