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

  Рет қаралды 40,003

Laravel Daily

Laravel Daily

2 жыл бұрын

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.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

Пікірлер: 93
@intipontt7490
@intipontt7490 2 жыл бұрын
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 Жыл бұрын
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 7 ай бұрын
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
@michaloravec14
@michaloravec14 2 жыл бұрын
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.
@joelmellon6868
@joelmellon6868 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 2 жыл бұрын
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 2 жыл бұрын
Something like that ? $rules = [ 'POST' => [ 'password'' => ['required'] ], 'PATCH' => [ 'password' => ['optional'] ] ]; return array_key_exists($this->method(), $rules) ? $rules[$this->method()] : [];
@ward7576
@ward7576 2 жыл бұрын
@@legato0 Yeah. Or use route names for keys.
@GergelyCsermely
@GergelyCsermely 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
@phpcoding9282
@phpcoding9282 2 жыл бұрын
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 Жыл бұрын
Great, exactly what I searched!
@johwel340
@johwel340 2 жыл бұрын
Chief thank you for the dark theme as well.
@inso4606
@inso4606 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 :)
@alila3883
@alila3883 2 жыл бұрын
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;
@KnightYoshi
@KnightYoshi 2 жыл бұрын
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
@bmtamim7818
@bmtamim7818 2 жыл бұрын
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😍
@gamerneversleep4200
@gamerneversleep4200 2 жыл бұрын
i make 2 request for update and store. Thanks for sharing 🙂.
@OnlinePseudonym
@OnlinePseudonym 2 жыл бұрын
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.
@kwameadoko9542
@kwameadoko9542 2 жыл бұрын
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; }
@tarekalhalabi8776
@tarekalhalabi8776 2 жыл бұрын
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💙
@liteninkiran
@liteninkiran 2 жыл бұрын
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 2 жыл бұрын
It turns out I needed "Accept" and "application/json" in the request header.
@ahmedrezwan3856
@ahmedrezwan3856 2 жыл бұрын
I personally like to use switch case on the basis of method for each different action.
2 жыл бұрын
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
@halzagh2891
@halzagh2891 2 жыл бұрын
thanks very interesting
@JamesAutoDude
@JamesAutoDude Жыл бұрын
Could always use a Service to call the same service under the store & update functions
@David-po3li
@David-po3li 2 жыл бұрын
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?
@michakoodziejczyk1848
@michakoodziejczyk1848 2 жыл бұрын
I use first approach, but if I have the same rules or similar I extend FormRequest one from another or from base one
@cactus_tit
@cactus_tit 2 жыл бұрын
I use to prepare merging validation, but now that I am looking to generate documentation automatically, its best to keep separate
@abdurroquib7051
@abdurroquib7051 2 жыл бұрын
If there is less conditions in the form requests class, this will be a best choice, otherwise two different class much more beneficial.
@TobiasOlssonHovby
@TobiasOlssonHovby 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 2 жыл бұрын
How is update class a child of store class in this hierarchy? Makes no sense. Tho it works.
@mabdullahsari
@mabdullahsari 2 жыл бұрын
Pretty sure the FormRequest won't be autovalidated if you do this.
@debjit21
@debjit21 2 жыл бұрын
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 2 жыл бұрын
Its easier to separate them. So you dont have to tell your team to do those except method and hashed password
@debjit21
@debjit21 2 жыл бұрын
@@werty2172 May be do when I refactor but for quick prototyping it is fine.
@werty2172
@werty2172 2 жыл бұрын
@@debjit21 its not
@debjit21
@debjit21 2 жыл бұрын
@@werty2172 Yes it is.
@werty2172
@werty2172 2 жыл бұрын
Okay. If u say so.
@bumblebity2902
@bumblebity2902 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 2 жыл бұрын
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
@Shez-dc3fn
@Shez-dc3fn 2 жыл бұрын
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
@kostjantin
@kostjantin 2 жыл бұрын
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 .... }
@oguz4158
@oguz4158 2 жыл бұрын
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?
@gabrielLlanesMX
@gabrielLlanesMX Жыл бұрын
Can I set a flash session message in FormRequest?
@thamibn
@thamibn 2 жыл бұрын
What if there's is no model route binding, how can you do the update with unique rule?
@imranlashari6578
@imranlashari6578 2 жыл бұрын
Different Store & Update with different requests
@gianfrancobriones
@gianfrancobriones 11 ай бұрын
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.
@gianfrancobriones
@gianfrancobriones 11 ай бұрын
answered my question 7:04 thanK you
@MrDragos360
@MrDragos360 2 жыл бұрын
What about using Auth::id() for getting the logged user id inside form request ? I use it and it works
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes, if you're editing your own user. But in this case, super-admin is editing ANOTHER user's profile.
@vovkko
@vovkko 2 жыл бұрын
As many requests as needed. First option
@arturkhachatryan63
@arturkhachatryan63 2 жыл бұрын
what theme do you use and font for phpstorm ? Thank you.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Material Darker theme
@arturkhachatryan63
@arturkhachatryan63 2 жыл бұрын
@@LaravelDaily Thank you!
@NOWAY-jg2lf
@NOWAY-jg2lf 11 ай бұрын
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 11 ай бұрын
Should be working!
@NOWAY-jg2lf
@NOWAY-jg2lf 11 ай бұрын
@@LaravelDaily Thank you, I was just worried if it might cause a security issue
@bdsumon4u
@bdsumon4u Жыл бұрын
UpdateRequest extends StoreRequest
@saranraj3708
@saranraj3708 2 жыл бұрын
What is two type of request in laravel?
@jemelo79
@jemelo79 Жыл бұрын
Diferent, most of the times they are diferent, sometimes they start the same and end diferent, so I just make two
@OnlinePseudonym
@OnlinePseudonym 2 жыл бұрын
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 2 жыл бұрын
I disagree, those are literally methods inside the Request class. If any class should be using them it's Request.
2 жыл бұрын
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 2 жыл бұрын
​@@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 2 жыл бұрын
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 :-)
@junaidhassan156
@junaidhassan156 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:"
@amrosdn
@amrosdn 2 жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Povilas has a short video too about the same topic kzbin.info/www/bejne/aYGVpoGbjp50sNU
@jijiwaiwai
@jijiwaiwai 2 жыл бұрын
I prefer to separate them which gives our maximum flexibility, you never know what weird requirements your client wants in the future 😂
@MahfuzurRahmanSaber
@MahfuzurRahmanSaber 2 жыл бұрын
While working with ajax how can i use form request ? I noticed $request->validated() doesn't work with ajax.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Not sure, should be working, not sure why it doesn't work for you.
@MahfuzurRahmanSaber
@MahfuzurRahmanSaber 2 жыл бұрын
@@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 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 2 жыл бұрын
Personally, that switch-case sounds too complicated for me, wouldn't it be possible to shorten it to if-else?
2 жыл бұрын
@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.
@soniablanche5672
@soniablanche5672 2 жыл бұрын
any reason why you used request() instead of $this ? you're inside a Request class after all.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
No reason, probably $this should work, too
@Realtek2super
@Realtek2super 2 жыл бұрын
Instead of $this->admin->id, I use auth()->id()
@LaravelDaily
@LaravelDaily 2 жыл бұрын
That's if you're updating your own record, right? But what if not?
@Realtek2super
@Realtek2super 2 жыл бұрын
@@LaravelDaily yes, only for updating.
2 жыл бұрын
@@Realtek2super Only if you want to ignore the currently logged in user.
@StefanKressCH
@StefanKressCH 2 жыл бұрын
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 2 жыл бұрын
First.
@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
9 Tips for Shorter Laravel Code
10:16
Laravel Daily
Рет қаралды 61 М.
Exceptions in Laravel: Why/How to Use and Create Your Own
12:18
Laravel Daily
Рет қаралды 87 М.
Mama vs Son vs Daddy 😭🤣
00:13
DADDYSON SHOW
Рет қаралды 47 МЛН
A teacher captured the cutest moment at the nursery #shorts
00:33
Fabiosa Stories
Рет қаралды 52 МЛН
Why Don't We Have A Laravel For JavaScript?
12:36
Theo - t3․gg
Рет қаралды 92 М.
Eloquent Soft Deletes: Things You May Not Know
10:57
Laravel Daily
Рет қаралды 21 М.
Laravel Pivot Tables: Simple to Advanced Many-to-Many
12:24
Laravel Daily
Рет қаралды 119 М.
Laravel: The BEST way to handle exceptions
9:29
Przemysław Przyłucki
Рет қаралды 15 М.
Laravel Service Providers: All You Need to Know
13:13
Laravel Daily
Рет қаралды 65 М.
Realtime with Laravel Reverb
1:19:36
Codecourse
Рет қаралды 5 М.
Laravel Routes: Grouping and Other "Tricks" - Challenge Result
7:41
Laravel Controller Code: Move to Model, Service, Action or Job?
12:51
Laravel Daily
Рет қаралды 105 М.
Jason made a fun pool in the Truck
0:21
Jason Vlogs
Рет қаралды 6 МЛН
Será Que a FITA vai Grudar ela na PAREDE😱 #shorts
0:44
Lucan Pevidor
Рет қаралды 62 МЛН
Я обещал подарить ему самокат!
1:00
Vlad Samokatchik
Рет қаралды 9 МЛН