Тёмный

One Reason to ALWAYS use Form Requests for Validation 

Laravel Daily
Подписаться 142 тыс.
Просмотров 24 тыс.
50% 1

I want to give you a strong argument on why validation logic in the controller is a violation of DRY and SOLID principles. Would you agree?
- - - - -
Support the channel by checking out our products:
- Enroll in my Laravel courses: laraveldaily.teachable.com
- Try our Laravel QuickAdminPanel: bit.ly/quickadminpanel
- Purchase my Livewire Kit: livewirekit.com
- View Laravel Code Examples: laravelexamples.com
- Subscribe to my weekly newsletter: bit.ly/laravel-newsletter

Хобби

Опубликовано:

 

15 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 174   
@rw5pVfd2pO
@rw5pVfd2pO 2 года назад
Always be sure to balance design with simplicity. While it is true that having inline validation violates SRP, I would argue that introducing a new class violates KISS for simple controllers. If you only have one action in the controller it would still be DRY without a separat form request class. If you add more actions and complexity to the controller, you should refactor - letting the design emerge because its required. Asking "what if you add this and that later" is often referred to as YAGNI or a code smell called speculative generality.
@bumblebity2902
@bumblebity2902 2 года назад
Some design principles contradicts each other.
@Jurigag
@Jurigag 2 года назад
Don't agree with YAGNI here. YAGNI is more about for example adding method of rclass that is never used(or only in tests), or adding some column and saving some information on table that is never used and stuff like this.
@dibbyo456
@dibbyo456 2 года назад
I agree.
@user-si3nz1dd9w
@user-si3nz1dd9w 2 года назад
Solid advice. These days, I tend to use Form Request objects even when I only need to validate a single input field. It really keeps things clean and organized, while also providing a proper way to do some minor transformations with the input or things related to that particular form by overriding the prepareForValidation() method inside your Form Request object.
@vovkko
@vovkko 2 года назад
finally someone say it to all juniors all over the world. Great start, waiting for next videos about solid
@ward7576
@ward7576 2 года назад
I would argue that the consistency aspect of always using form requests is the selling point of itself + there could be a situation where we need some additional fields validated, therefore we already have a dedicated form request class where to put additional validation logic.
@max7579
@max7579 2 года назад
I am a fan of sacrificing a little KISS for the sake of easier maintainability in the future. The fewer lines added to my team's PRs the better and anticipating future modification can be a big help in that. Consistent use of FormRequests even for just 1 field is a good example of this
@ward7576
@ward7576 2 года назад
@@max7579 yeah, true. But that comes with proper planning.
@malamhari_
@malamhari_ 2 года назад
Great advice, thanks! Can't wait for the SOLID one
@kinvain
@kinvain 2 года назад
Great video but just a quick comment. SRP (Single Responsibility Principle) is not about how many things a class does (one or least as possible). SRP is about that class should have only one reason to be changed. The example with mixing validation and creating demonstrates it very clear. When we have validation rules and then call `Product::create` now we have at least two reasons to change this class. First, when we change validation rules. Second, when we change what we call to store a product. I always try to explain that validation is not a part of a "business logic". Yes, it should be executed before we create an object, but creational service should not care about any rules. It only needs to know how to create an object and maybe notify about the success or failure.
@LaravelDaily
@LaravelDaily 2 года назад
Thanks for this additional very valuable comment.
@josechirino5168
@josechirino5168 2 года назад
Congratulations for the 70k subscribers, you deserve it
@yazankaake5282
@yazankaake5282 2 года назад
Soft, light, easy to understand, and contain great ideas Really this my opinion about your videos Wish you alll success 🌹🌹
@beatnu187
@beatnu187 2 года назад
Good argument! thank you! have a nice Sunday!
@belce1982
@belce1982 2 года назад
Thank you as always. Keep going! Don't stop now!
@andreasbrunsmann3408
@andreasbrunsmann3408 2 года назад
And again...after watching one of your clips my todo list grows instantly :D
@phamluong5419
@phamluong5419 2 года назад
Thank you for your advice. Looking forward to your solid video.
@boriakhi
@boriakhi 2 года назад
The inline validation was one of the first things I noticed about Laravel and assumed it was the standard with Laravel. Yii is very explicit where the validation rules should be and I preferred it Thanks for sharing this.
@tenariusstuff7303
@tenariusstuff7303 2 года назад
Hi Laravel Daily, thanks for all your free high quality laravel tutorials on youtube. Your payable courses are short, simplified and on the point, too. It´s easy for me to follow you and I learned a lot since I know your channel. Thanks and go on bro!
@LaravelDaily
@LaravelDaily 2 года назад
Glad you like them!
@BenjaminHaeberli
@BenjaminHaeberli 2 года назад
Love it ! I'm always using Form Request, it helps to keep things clean and organized 😉
@dinkodugec9184
@dinkodugec9184 Год назад
So, after Many tutorails on your channel, IT seems That Laravel daily is better resource than documentation.. my opinion!!
@ShakeelAhmed-jk7cn
@ShakeelAhmed-jk7cn 2 года назад
Great advice, thanks fo sharing Sir!
@GergelyCsermely
@GergelyCsermely 2 года назад
I vote for FormRequest too. You can place also the access controll in that.
@zafarbekbadalboyev9689
@zafarbekbadalboyev9689 2 года назад
Great advice, bro. Thanks
@vatsalpatel3669
@vatsalpatel3669 2 года назад
I always like to use the form request and also like the idea behind that vary much 👍😊
@siulacio
@siulacio 2 года назад
Excelent! thank you so much.
@ivan_adamovich
@ivan_adamovich 2 года назад
Thank you for your videos
@ChangeYourLifeForever
@ChangeYourLifeForever 2 года назад
i tried Form Request Validation and it help also for authorizations as well .
@felipeveiga87
@felipeveiga87 2 года назад
Thanks from Brazil
@_Welter_
@_Welter_ 2 года назад
Great advice.
@farazsalehi9034
@farazsalehi9034 2 года назад
Greate Advice Thank Q.
@prshendra
@prshendra 2 года назад
I am waiting you SOLID video on laravel 🙏🤩
@nikza1936
@nikza1936 2 года назад
Without doubts the best way.
@coding_david
@coding_david 2 года назад
Great advice & interesting aspect! I am currently using both in my project. One thing that sometimes prevents me from using form requests is the fact that form requests are done as the first thing in the controller function. Sometimes however, I need to do other things first in the controller, before validating the data that has been handed over.
@LaravelDaily
@LaravelDaily 2 года назад
Yes for more complicated cases it happens. But then you have prepareForValidation() method. Can you give an example case, and I will shoot a separate video for you.
@coding_david
@coding_david 2 года назад
@@LaravelDaily Yes you are right, the prepareForValidation() function is great for merging values before validation, that I am using as well. To be honest I haven't found a good example because - after your comment - I realized that some controllers could be enhanced by moving a lot more stuff to the preparation function.. will give that a try and let you know if I encounter something that would be an example for keeping it in the controller.
@ahmdalgendi
@ahmdalgendi 2 года назад
good morning from Egypt
@justtestingmycurrentskills747
@justtestingmycurrentskills747 2 года назад
Excellent Thumbnail.
@laayounelive2020
@laayounelive2020 2 года назад
Thanks
@arashpirhadi1326
@arashpirhadi1326 2 года назад
100% Agreeable.
@eOssa
@eOssa 2 года назад
In my begining with Laravel I used the FormRequest, but that approach was very confusing for me as junior, therefore I prefer the inline validation.
@candraliao7466
@candraliao7466 2 года назад
Hi, I have seen this video. It is perfect. May u create this video complete?
@akramzad
@akramzad 2 года назад
Great information 👍 Thanks for the video and i would to know why u prefer using ResourceCollection instead the normal response json
@TheMediinaa
@TheMediinaa 2 года назад
Hello friend. The way I see it, you use a resource to "serialize" your model data. For example, maybe for a given model you're never interested in returning the id field, or created_at and updated_at fields, or you even maybe have to change some field in some way; the place where you can't put this logic is in a Resource (or a Resource Collection if you give a Collection to the constructor of the resource).
@LaravelDaily
@LaravelDaily 2 года назад
For consistency if I need to reuse that Resource somewhere else.
@RizkheyG
@RizkheyG 2 года назад
I Agree with Form request class documentation should be bit higher, TBH I don't know this class until recently(well you know for me to come to that page only to see the rules I need and LOTS of tutorials always teach me to use inline validation in controller). Laravel doc should put some "best practice" how to use Laravel in it's documentation site.
@AddMotionLeb
@AddMotionLeb 2 года назад
Great
@gustavovasquezveliz7046
@gustavovasquezveliz7046 2 года назад
Sometimes is too overkill. Keep it simple, refactor only when necessary
@Ibrahim_usman
@Ibrahim_usman 2 года назад
Quick question. How do you do multiple FormRequest validation on a single request? For example I have 5 fields. if 3 fields are present make the 1st and 5th field required. but if two fields are present, make 3rd and 4th field required. I could do two FormRequest but I'm sure if I pass the first FormRequest arguments in the other I will get a type error.
@Semicolon..
@Semicolon.. 2 года назад
The best way in my opinion is to keep everything separated 👍🏻
@mostafaharb81
@mostafaharb81 Год назад
Mostly, I don't prefer going through request class validation and do prefer inline validation. Although request class makes it easier to control project on line term and from a single file, but handling the behaviour of failure would not be as intended.. sometimes I would like to insert some of the data even if errors exist and do a specific behaviour accordingly.. if their was a way to control that from request class then its okay, but if it also being used in api, then that would make things more complicated.. personally I do preffer to add a service with validator inside it,and do the logic in service and return results always as array, and inside the controller I just return data as needed, if request was from api then I return json , else return view or redirect.
@bn646
@bn646 2 года назад
Thanks Mr. Povilas for awesome lessons. How do I validate unique some fields when update with FormRequest ? I looked on the google but I did not found exact solution.
@LaravelDaily
@LaravelDaily 2 года назад
Will shoot a video about it
@soniablanche5672
@soniablanche5672 2 года назад
The controller should link the model with the view, so creating the model inside the controller is perfectly fine.
@irhamumam2611
@irhamumam2611 2 года назад
Can i implement form request with unique softdelete validation?
@phamthao5421
@phamthao5421 2 года назад
sometimes i want to use queried record in validate FormRequest like unique or exist in controller and there is no way to do that, i need to query again in controller so i use validate in controller. Of course i can use some memoization lib like spatie/once to fix that in FormRequest.
@terratails0001
@terratails0001 Год назад
Can you make a video explaining how to redirect a form page depending on what radio button you submit?
@xnetwork7691
@xnetwork7691 2 года назад
Hey, what theme and icon set do you use in your videos? Thanks in advance!
@LaravelDaily
@LaravelDaily 2 года назад
Phpstorm theme Material darker
@once6833
@once6833 2 года назад
Thumbnail made me watch this lmao
@Juanylosdelcampo
@Juanylosdelcampo 2 года назад
When I use the FormRequest to set the rules as required, instead of placing them on the controller inside the validate() method, if I delete the key from the field in the Json Postman Body, updates without errors, just without the field I deleted but was required. Placing the rules inside the controller gives me the error "The field is required", that that is what i' m looking for. Do you know what can I do? Thanks!!
@holonaut
@holonaut 2 месяца назад
Just reuse your own validators, nothing wrong with that.
@bboydarknesz
@bboydarknesz 2 года назад
sometimes in crud, create and update almost have same validation. is that mean I should make more than one RequestValidation too? I rare use it, but I think yes is the answer. thats why your naming is start from "Store" thanks
@LaravelDaily
@LaravelDaily 2 года назад
Yes, usually I separate them, but it's a personal choice and depends on the situation. Planned to shoot a separate video.
@MrMatni45
@MrMatni45 2 года назад
hi i this how it should be to cater for both store and update request and without route parameter.. or i can clean up this code and also..im using the jsvalidator that you post recently... $rules = []; if(isset($this->id)) { $rules['id'] = 'required'; $rules['name'] = ['required', Rule::unique('mdt_menu', 'men_name')->whereNull('deleted_at')->ignore($this->id, 'men_id')]; }else{ $rules['name'] = ['required', Rule::unique('mdt_menu', 'men_name')->whereNull('deleted_at'); } $rules['url'] = ['required']; return $rules;
@stojankukrika7242
@stojankukrika7242 2 года назад
I didn't find how to do form requests in lumen applications(microservice instances) so use inline validations. Maybe someone know how to validate that :)
@mohitlandge5683
@mohitlandge5683 2 года назад
I have this kind of validation rule in updateProductRequest 'name' => 'required|max:200|unique:products,name,' . $id, but I need id to verify unique name on update How should I pass Id to the request file which I need to perform validations? Thank you in advance
@abdmaster
@abdmaster 2 года назад
I always use form request. However sometimes I need to validated inputs for CLI / Console. That time I use Validator::make() in there. Wish could use the FormRequest in Console too..
@LaravelDaily
@LaravelDaily 2 года назад
You can get the rules from FormRequest and reuse them from wherever, something like: $rules = (new App\Http\Requests\StoreUserRequest)->rules();
@bagasadifirdaus9278
@bagasadifirdaus9278 2 года назад
Thanks sir. I dont know there is a form request...
@user-qz6oj3tc3z
@user-qz6oj3tc3z 10 месяцев назад
I always use form request
@JouvaMoufette
@JouvaMoufette 2 года назад
I always use form requests over inline validation. But I'm not a fan of what you need to do if you want to use the unique validation for updates. It's a somewhat ugly flow to attach the ID to the validate statement to prevent editing a record without changing the unique field triggering a validation error
@LaravelDaily
@LaravelDaily 2 года назад
Yes, that's a good point, I don't like that either.
@lingaung7880
@lingaung7880 Год назад
Sir could u like to share how to solve form request validation unique update?
@PathOfDamn
@PathOfDamn 2 года назад
Say we have slightly different requests for update and store, do we create two separate Request files for them?
@LaravelDaily
@LaravelDaily 2 года назад
It depends on the situation, it's your choice. Will shoot a video about it, added to the to-do list.
@PathOfDamn
@PathOfDamn 2 года назад
@@LaravelDaily Thank you! Looking forward to it
@ravikhatri24
@ravikhatri24 2 года назад
How would i do 3 different model create using formrequest ? Like product, user, order form submitted and all i get is one variable having three models data and i have to manually validate set of variable from the group of submitted values...?
@LaravelDaily
@LaravelDaily 2 года назад
It depends on the structure, so hard to comment, maybe provide a specific example, but generally you can pass all of that into the rules, like 'products.*' => 'required' or something like that.
@myfavorites5602
@myfavorites5602 Год назад
when i use by ajax i have error 422 Unprocessable Content
@msdeav
@msdeav 2 года назад
Personally, I use inline validation. It is easier to copy and paste from Store:validation to Update:validation and quickly change required lines. Even in this case, I'm not sure there will be always the same parameters in WEB and API. And you'll end up creating new request files for each one.
@haroldpepete
@haroldpepete 2 года назад
great video, code looks cleaner and controller has only few lines. i have two question sr, code inside method controller is executed only if validation pass?, what happen if validation fail in api and html view?
@LaravelDaily
@LaravelDaily 2 года назад
Yes, Controller code is executed only if validation passes. I will shoot a separate video on how to separate html and api.
@haroldpepete
@haroldpepete 2 года назад
@@LaravelDaily thank for your time
@kyjovs7746
@kyjovs7746 2 года назад
Is it possible to bypass the form request for specific functions? Lets say, I have a user form request for create and update. But as for update password, some of the rules on the said request aren't necessary anymore. Or should I just create a different validation for that?
@LaravelDaily
@LaravelDaily 2 года назад
I personally create a different form request for update. But it's your choice. I will shoot a separate video on how to use the same form request file for create/update.
@kyjovs7746
@kyjovs7746 2 года назад
@@LaravelDaily Thanks!
@muhammadmurtaza9896
@muhammadmurtaza9896 Год назад
How to bcrypt password or store file using request class
@abdulbasitsalah2918
@abdulbasitsalah2918 2 года назад
the only reason i use inline validation because i work with api, and i went to return all the error message in a single array. like below👇 { "status": 422, "message": [ "The email field is required.", "The password field is required." ] } this achieved by using, "$validator->errors()->all()" //validation $validator = Validator::make($request->all(), [ 'email' => ['required', 'email'], 'password' => ['required', 'string'], ]); if ($validator->fails()) { return response()->json([ 'status' => 422, 'message' => $validator->errors()->all() ], 422); } is there away to return all the message in form request ?
@LaravelDaily
@LaravelDaily 2 года назад
You can globally override validationexception, like I did in this video with another exception: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-SlBJrLnyoMk.html
@shaungbhone8368
@shaungbhone8368 2 года назад
What about the request validation failed?
@LaravelDaily
@LaravelDaily 2 года назад
What about it?
@krishnanarasimha1243
@krishnanarasimha1243 2 года назад
How can i change the user defined validation with messages to registration form
@abdulbasitsalah2918
@abdulbasitsalah2918 2 года назад
if you mean return costume message, you can use this $messages = [ 'old_password.required' => __('api.old_password_req'), 'new_password.required' => __('api.new_password_req'), 'old_password.min' => __('api.old_password_min'), 'new_password.min' => __('api.new_password_min'), ]; //validation $validator = Validator::make($request->all(), [ 'old_password' => ['required', 'string', 'min:8'], 'new_password' => ['required', 'string', 'min:8'], ], $messages);
@user-si3nz1dd9w
@user-si3nz1dd9w 2 года назад
If you use a Form Request object, you can add a messages() method to it that returns an array with inputs and rules that you want to have a custom message, like that: [ 'email.required' => 'Please enter your e-mail address', ... ];
@mohammedabdalla6452
@mohammedabdalla6452 2 года назад
Can i use the same form request with livewire?
@LaravelDaily
@LaravelDaily 2 года назад
Unfortunately not.
@assanesambagueye4132
@assanesambagueye4132 2 года назад
Hello! Can we use form request with livewire?
@LaravelDaily
@LaravelDaily 2 года назад
Unfortunately not
@assanesambagueye4132
@assanesambagueye4132 2 года назад
I see thanks!
@marcusgaius
@marcusgaius 2 года назад
I keep getting validation error messages in wrong locale. Does anyone know how to fix that? I have locale set in the controller method that shows the form. Where can I set locale for the post request that is being validated?
@marcusgaius
@marcusgaius 2 года назад
Possible rubber duck moment, will test when I get home. :D
@LaravelDaily
@LaravelDaily 2 года назад
Locale should be set not in the controller, but somewhere much earlier, like global Middleware or something.
@marcusgaius
@marcusgaius 2 года назад
Thank you so much! :) The best thing I came up with was a (very) hacky way of adding initialize method to my form request, setting locale there based on php $_POST and then calling the parent initialize. Even though I was content with finding a way, I was sure someone would point me to the proper way. I did it with middleware this morning. :D
@TheMediinaa
@TheMediinaa 2 года назад
Say I have a list of comments and I only want to allow the author of those comments to edit them. Should I leave the "authorization" logic in middleware, authorize method of FormRequest or a service?
@LaravelDaily
@LaravelDaily 2 года назад
It's a personal preference. I would create a Policy for that.
@TheMediinaa
@TheMediinaa 2 года назад
@@LaravelDaily Cool, I put it in a middleware at first, but my senior collegues said a middleware should be more generic to be applied to more routes, instead of very specific to one route. I have to study Policies then, thanks for the reply! >D
@LaravelDaily
@LaravelDaily 2 года назад
Probably watch this video: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-kZOgH3-0Bko.html
@TheMediinaa
@TheMediinaa 2 года назад
@@LaravelDaily ended up creating a Policy haha
@holonaut
@holonaut 2 месяца назад
Can I get your opinion on the following: In my company there is this habit of passing request objects (like the one you've shown in the video) around in the entire application. A lot of services and sometimes even model methods rely on getting a request passed in. Imo this is completely deranged, because Request objects in Laravel are built from globals. I'd much prefer if people would just rely on either scalar parameters or plain old objects, rather than these monsters.
@LaravelDaily
@LaravelDaily 2 месяца назад
Yes, in theory you're right. A common practice is also DTOs or Value Objects if you want to systematize it. But in practice, it's often "whatever works don't touch it" :)
@CarlosCarucce
@CarlosCarucce 2 года назад
Not a "downside" properly. But I cant figure out why one of my requests displays laravel default homepage when validation fails instead of the error message or a "non 2XX" http code in an API controller.
@LaravelDaily
@LaravelDaily 2 года назад
I will shoot a separate video about it, I see many people asking for it, so need a video :)
@CarlosCarucce
@CarlosCarucce 2 года назад
Looking forward to this. Thank you!
@mityukov
@mityukov 2 года назад
Jeffrey's voice: "but it's this really better?" You state that validation is not a controller's concern and make all further arguments from this position. I say that validation actually belongs here, unless it is complex enough to want to move it outside. For me, it's more convenient to see the following right inside controller: - validation - what it does (to the model, etc) - the response format There was even an advice from Reinink to move queries to peripherals (with good reasons to do so), for instance. So, to conclude: i think that knowing solid/dry/etc is, actually, very helpful. But it is also very important to understand where they help more than hurt.
@user-si3nz1dd9w
@user-si3nz1dd9w 2 года назад
It might work if your app is mostly made of simple and straightforward CRUD operations, and if you stay consistent with this approach (i.e. not switching between inline validation and Form Request from controller to controller). But if there is a lot of complex logic that needs to validate relationship association etc., you would go mad cramming it all into controllers. That's exactly when the issue arises: you have some simple stuff validated right on the controller, and then you have this complex validation in some other place moved to a Form Request object with Rule classes and stuff. In practice, it quickly turns development into nightmare in any relatively big or complex project as you add a reduntant cognitive pattern of making decision of "Where did I put that shit 6 months ago?! Ah, yes...".
@LaravelDaily
@LaravelDaily 2 года назад
I agree, but then it complicates the learning process for new people and they get conflicting advice - in this case do X, in that case do Y, etc. I think it's better to adapt one strategy and just keep creating form request classes and stick to it. Or, validate everything in controllers and stick to it. So I've stated my position in this video, with arguments. Sure, it's not the sacred rule, but one fewer question to ask yourself "where to put X" and move on to more important questions.
@mityukov
@mityukov 2 года назад
@@LaravelDaily yeah, the consistency is important too. But there's one other point that i, for instance, have to consider: who you expect to be mending for this code (besides yourself). In my practice, it is more often a person with a general php knowledge, than someone, who knows it all about your framework of choice. (Offtop) it is very interesting, though: Google trends clearly show that Laravel is very popular, but in my country it's easier to find someone with Yii expertise than with Laravel... But sure how come...(/offtop) And, speaking of "general php code": it is not intuitive (without decent Laravel background) that a class, typehinted on the controller method's argument, actually does something like validation or authorization. `$request->validate(...)` is way more intuitive for a 'proficient in php, but not too much into Laravel specifically' dev, who you invite to your project.
@LaravelDaily
@LaravelDaily 2 года назад
That's a very VERY good point - will even post it on Twitter. Now I clearly see the difference in comments - from people who come to Laravel after a long experience with plain PHP or other framework like Yii, vs people who started with Laravel and never knew any other. So yes, then opinions are very different, and audience is different. On this channel, I'm not teaching PHP and not trying to do it the PHP way. I'm trying to explain how to use the framework that we all love to its fullest potential. The channel is "Laravel Daily", not "PHP Daily" :)
@MartinBojmaliev
@MartinBojmaliev 2 года назад
Sometimes when we have unique field and try to update a Model, usually we use the unique rule providing which ID to ignore. How do we do that using Form Requests? How we can access the data?
@LaravelDaily
@LaravelDaily 2 года назад
I guess I need to shoot a separate video for it, at least a few people ask the same thing
@MartinBojmaliev
@MartinBojmaliev 2 года назад
@@LaravelDaily thank you I appreciate it
@intipontt7490
@intipontt7490 2 года назад
Technically, you could argue the Model is the class responsible for creating the product so there's no need to create a separate class for it.
@LaravelDaily
@LaravelDaily 2 года назад
Well, yes, model is responsible for CREATING the product but not VALIDATING INPUT. Technically you may be right, but it's not typical practical thinking in Laravel.
@intipontt7490
@intipontt7490 2 года назад
@@LaravelDaily Yes, I agree with using FormRequests. I meant there's no need to create a separate Action/Service for creating the Model after the input is validated.
@castromarvel1938
@castromarvel1938 2 года назад
How can i pass custom messages in form request
@LaravelDaily
@LaravelDaily 2 года назад
The docs: laravel.com/docs/9.x/validation#customizing-the-error-messages
@castromarvel1938
@castromarvel1938 2 года назад
@@LaravelDaily thanks
@MrStealthWarrior
@MrStealthWarrior 2 года назад
Wouldn't form requests be created once more for API if you have some optional fields on them? Because when you validate form from your laravel app, those fields should be nullable, while in case of API they could be either valid or missing. Which would make your code inconsistent. Some form validations used in both cases, some copied almost the same.
@LaravelDaily
@LaravelDaily 2 года назад
Of course, it depends. In some cases, you do need separate form request classes, or you could have the same form request class and rules() should be dynamic with if statement if request comes from API. There's no one rule, it's all personal preference.
@user-si3nz1dd9w
@user-si3nz1dd9w 2 года назад
One way to keep things clean and consistent in these cases while still using the Form Request objects, would be to add another level of abstraction in the same manner that we use the Repository pattern along with our models. Let's say you have two endpoints for external and internal API feeding from the same logic domain. You can add a separate class that holds validation rules (and even messages, if needed) for these endpoints as separate methods, and then you call these methods inside the Form Request object dynamically depending on the request being sateteful or stateless ($this->wantsJson()). It helps to avoid creating a lot of spaghetti in both Form Request and Controller while keeping the necessary logic and static properties close to its domain.
@erlangparasu6339
@erlangparasu6339 2 года назад
for me.. naming the request classes is difficult 😂
@LaravelDaily
@LaravelDaily 2 года назад
I personally always name [Store|Update][ModelName][Request], like StoreUserRequest or UpdateUserRequest
@Felx645
@Felx645 2 года назад
What about having only one field to validate and you only care whether it exists or not (so required rule) Wouldnt it be better (in terms of overengineering) to just use !$request->has() and then abort?
@MrStealthWarrior
@MrStealthWarrior 2 года назад
Form validation lets you construct good response if some fields do not pass validation
@LaravelDaily
@LaravelDaily 2 года назад
In my opinion, it's about habits. So just get used to use form requests and then you don't need to think how to do it each time differently.
@Felx645
@Felx645 2 года назад
Yeah, makes sense
@wildfireDZ
@wildfireDZ 2 года назад
Creating a FormRequest file for every request is a mess. I prefer having them in service function where i can pass action (store or update) and so have same rules and not repeating for store and update
@LaravelDaily
@LaravelDaily 2 года назад
I will shoot a video soon where you can use the same form request for store and update, even if the rules are different.
@iarman8474
@iarman8474 2 года назад
Using Form Request is a good practice but I refused to use it because I couldn't append data to the validated requests. I wanted to append user_id to $request->validated() method but it seems like it is not possible.
@LaravelDaily
@LaravelDaily 2 года назад
Why not possible? $request->validated() + ['user_id' => $whatever]
@iarman8474
@iarman8474 2 года назад
@@LaravelDaily I mean in Form Request class not in Controller
@LaravelDaily
@LaravelDaily 2 года назад
You can use prepareForValidation maybe? dev.to/arielmejiadev/prepareforvalidation-method-in-laravel-form-requests-29ao
@holonaut
@holonaut 2 месяца назад
@@LaravelDaily I have to deal with projects where there are FormRequests with 3-4 levels of inheritance passed around in the application, where each one of them adds its own garbage via methods like prepareForValidation(). Truly nothing makes me more mad than this.
@alexandrugojinetchi6058
@alexandrugojinetchi6058 2 года назад
I don't use Form Request , actually i can't understand that thing , why i have to declare a new class what is used just to validate one array and it become weird when you have many controllers with 5+ methods into each controller. I tried to use it but i couldn't...
@holonaut
@holonaut 2 месяца назад
It's an imaginary solution to an imaginary problem. You can just use a function if you wanna reuse a piece of code. And in fact functions are much more reusable (in more places) than these weird FormRequests that interact with global state in order to be constructed. It's extremely annoying how they are sold as some superior thing when they really just mix the worst practices of OOP and procedural programming into one giant mess.
@sucheabey2014
@sucheabey2014 2 года назад
how can we use Form Requests for Validation on livewire?
@LaravelDaily
@LaravelDaily 2 года назад
You can't
@sucheabey2014
@sucheabey2014 2 года назад
@@LaravelDaily thanks
@sucheabey2014
@sucheabey2014 2 года назад
@@LaravelDaily Does we have any ways?
@LaravelDaily
@LaravelDaily 2 года назад
Next time please google and read the official docs. I googled "Livewire form requests", quote from the official docs. Due to the nature of Livewire, hooking into the http request wouldn't make sense. For now, this functionality is not possible or recommended.
@sucheabey2014
@sucheabey2014 2 года назад
@@LaravelDaily ok, thank so much
@julienSibille
@julienSibille 2 года назад
When you have a lot of models and CRUD controller operations, the app/Request folder starts being dirty, especially if you need Store and Update files for each CRUD
@UnknownUser-ud1es
@UnknownUser-ud1es 2 года назад
I solved this issue by using laravel module package. Works like a charm.
@user-si3nz1dd9w
@user-si3nz1dd9w 2 года назад
You can simply segregate those classes by directories inside the app/Http/Requests directory, like: app/Http/Requests/Checkout or app/Http/Requests/User, etc. Just set the correct namespace, or generate them via artisan command, specifying the folder, and then Artisan will set the correct namespace for you. It really helps to keep things organized, especially if you prefer to work with a mouse and a sidebar in the IDE instead of IDE's quick search.
@julienSibille
@julienSibille 2 года назад
@@UnknownUser-ud1es As the doc says : "This package is supported and tested in Laravel 5", far away from 8.x isn't it ?
@julienSibille
@julienSibille 2 года назад
@@user-si3nz1dd9w Yes this is some clean option, you still have a lot of subfolders instead of a lot of files, but this is the way i prefer
@LaravelDaily
@LaravelDaily 2 года назад
Personally, I prefer dirty Requests folder (which can be cleaned up with subfolders) than dirty controllers.
@jeroenvanrensen9505
@jeroenvanrensen9505 2 года назад
I don’t agree. Although you’re violating SOLID, it keeps the code much simpler. I would only use form requests when building an API.
@LaravelDaily
@LaravelDaily 2 года назад
You have the right to not agree, that's the beauty of what we all do here. But I don't really understand the argument - how API validation is different from Web? Why form requests for API and not Web?
@edwinencomienda
@edwinencomienda 2 года назад
So basically you’re saying what IFs. For me if it needs to use it then use it rather than using it all the time which doesn’t make sense for small simple projects
@LaravelDaily
@LaravelDaily 2 года назад
It's a matter of habit. If you do it automatically for any project, small or big, then you have one fewer question on how to do it in the future, and focus on other more important questions.
@edwinencomienda
@edwinencomienda 2 года назад
@@LaravelDaily Yes you have point But don’t forget about simplicity and lesser abstraction easier to read. There are cases that inline might be suitable. for me “Would you use washing machine to wash a single shirt? it’s better to wash it by hand so it’s easier rather than putting extra effort” 🙂
Далее
9 Tips for Shorter Laravel Code
10:16
Просмотров 61 тыс.
▼ЕГО БОЯЛИСЬ МОНГОЛЫ 🍣
32:51
Просмотров 294 тыс.
Don't throw exceptions in C#. Do this instead
18:13
Просмотров 253 тыс.
To-Do App in Assembly
1:05:27
Просмотров 120 тыс.
Eloquent Polymorphic Relations: Properly Explained
9:56
Laravel SPA Authentication - setup and common mistakes
16:55
Laravel Junior Code Review: 12 Tips on Everything
15:30
18 Laravel/PHP Tips in 10 Minutes: June 2024
10:41
Просмотров 8 тыс.
Дети взломали аттракцион😱
0:21
10 июля 2024 г.
0:34
Просмотров 1,7 млн
Фонтанчик с черным…
1:00
Просмотров 1,7 млн
Easier when using this tip
1:00
Просмотров 14 млн