Laravel Form Request: Store/Update - Same or Separate Class?
Вставка
- Опубліковано 9 лис 2024
- 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-...
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 )) ]
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 !
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
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.
Something like that ?
$rules = [
'POST' => [
'password'' => ['required']
],
'PATCH' => [
'password' => ['optional']
]
];
return array_key_exists($this->method(), $rules) ? $rules[$this->method()] : [];
@@legato0 Yeah. Or use route names for keys.
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!
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
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.
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😍
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 :)
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
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💙
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;
}
i make 2 request for update and store. Thanks for sharing 🙂.
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.
Chief thank you for the dark theme as well.
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;
I personally like to use switch case on the basis of method for each different action.
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.
Its easier to separate them. So you dont have to tell your team to do those except method and hashed password
@@werty2172 May be do when I refactor but for quick prototyping it is fine.
@@debjit21 its not
@@werty2172 Yes it is.
Okay. If u say so.
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 ....
}
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.
It turns out I needed "Accept" and "application/json" in the request header.
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
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.
How is update class a child of store class in this hierarchy? Makes no sense. Tho it works.
Pretty sure the FormRequest won't be autovalidated if you do this.
Great, exactly what I searched!
Could always use a Service to call the same service under the store & update functions
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?
I use first approach, but if I have the same rules or similar I extend FormRequest one from another or from base one
If there is less conditions in the form requests class, this will be a best choice, otherwise two different class much more beneficial.
Using OOP extends magic, to inherit store class info and modify or use switch/case approach, usually what I've seen in Laravel forums.
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
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?
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
As many requests as needed. First option
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?
Different Store & Update with different requests
What about using Auth::id() for getting the logged user id inside form request ? I use it and it works
Yes, if you're editing your own user. But in this case, super-admin is editing ANOTHER user's profile.
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.
answered my question 7:04 thanK you
what theme do you use and font for phpstorm ? Thank you.
Material Darker theme
@@LaravelDaily Thank you!
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 ?
Should be working!
@@LaravelDaily Thank you, I was just worried if it might cause a security issue
Can I set a flash session message in FormRequest?
What if there's is no model route binding, how can you do the update with unique rule?
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.
I disagree, those are literally methods inside the Request class. If any class should be using them it's Request.
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.
@@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.
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 :-)
UpdateRequest extends StoreRequest
What is two type of request in laravel?
thanks very interesting
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?
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:"
While working with ajax how can i use form request ? I noticed $request->validated() doesn't work with ajax.
Not sure, should be working, not sure why it doesn't work for you.
@@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. 😕
I prefer to separate them which gives our maximum flexibility, you never know what weird requirements your client wants in the future 😂
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.
Personally, that switch-case sounds too complicated for me, wouldn't it be possible to shorten it to if-else?
@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.
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
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 👏
Povilas has a short video too about the same topic
ua-cam.com/video/3P2uNeY9Azs/v-deo.html
Diferent, most of the times they are diferent, sometimes they start the same and end diferent, so I just make two
Instead of $this->admin->id, I use auth()->id()
That's if you're updating your own record, right? But what if not?
@@LaravelDaily yes, only for updating.
@@Realtek2super Only if you want to ignore the currently logged in user.
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....
any reason why you used request() instead of $this ? you're inside a Request class after all.
No reason, probably $this should work, too
First.
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