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

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

Laravel Daily

2 года назад

39,416 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

D. A.
D. A. - 03.10.2023 07:02

sometimes|required_without:id

Ответить
NO WAY
NO WAY - 20.08.2023 10:10

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 ?

Ответить
Gianfranco Dy
Gianfranco Dy - 18.08.2023 06:43

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.

Ответить
JamesAutoDude
JamesAutoDude - 15.01.2023 13:21

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

Ответить
Sébastien Faut
Sébastien Faut - 15.12.2022 22:57

Great, exactly what I searched!

Ответить
Gabriel Llanes
Gabriel Llanes - 24.11.2022 23:05

Can I set a flash session message in FormRequest?

Ответить
Sumon Ahmed
Sumon Ahmed - 11.11.2022 10:50

UpdateRequest extends StoreRequest

Ответить
José Melo
José Melo - 11.11.2022 00:06

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

Ответить
Junaid Hassan
Junaid Hassan - 07.08.2022 01:46

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?

Ответить
saran raj
saran raj - 12.06.2022 15:38

What is two type of request in laravel?

Ответить
Corbin Jurgens
Corbin Jurgens - 02.02.2022 10:54

I use to prepare merging validation, but now that I am looking to generate documentation automatically, its best to keep separate

Ответить
oguz
oguz - 19.01.2022 17:15

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?

Ответить
Mahfuzur Rahman Saber
Mahfuzur Rahman Saber - 18.01.2022 14:32

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

Ответить
Kiran Anand
Kiran Anand - 05.10.2021 17:54

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.

Ответить
David
David - 04.10.2021 06:03

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?

Ответить
InSO
InSO - 15.09.2021 23:35

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 :)

Ответить
Joel Mellon
Joel Mellon - 09.09.2021 23:57

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!

Ответить
Michał Koodziejczyk
Michał Koodziejczyk - 09.09.2021 12:01

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

Ответить
Kostia Muliar
Kostia Muliar - 08.09.2021 15:19

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

Ответить
thamibn
thamibn - 07.09.2021 14:45

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

Ответить
Amro Hassan
Amro Hassan - 06.09.2021 16:05

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

Ответить
Imran Lashari
Imran Lashari - 06.09.2021 10:19

Different Store & Update with different requests

Ответить
Dragos
Dragos - 06.09.2021 09:59

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

Ответить
Michal Oravec
Michal Oravec - 06.09.2021 00:34

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.

Ответить
Knight Yoshi
Knight Yoshi - 05.09.2021 23:50

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

Ответить
Abdur Roquib Pramanik
Abdur Roquib Pramanik - 05.09.2021 23:33

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

Ответить
Tarek Alhalabi
Tarek Alhalabi - 05.09.2021 22:03

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💙

Ответить
Kwame Adoko
Kwame Adoko - 05.09.2021 21:23

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;
}

Ответить
ahmed rezwan
ahmed rezwan - 05.09.2021 20:23

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

Ответить
Shez 1983
Shez 1983 - 05.09.2021 20:04

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

Ответить
Artur Khachatryan
Artur Khachatryan - 05.09.2021 20:01

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

Ответить
唧唧歪歪
唧唧歪歪 - 05.09.2021 16:20

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

Ответить
Anderson García Ascanio
Anderson García Ascanio - 05.09.2021 16:11

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

Ответить
Sonia Blanche
Sonia Blanche - 05.09.2021 15:52

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

Ответить
OnlinePseudonym
OnlinePseudonym - 05.09.2021 14:46

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.

Ответить
OnlinePseudonym
OnlinePseudonym - 05.09.2021 14:43

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.

Ответить
Realtek2super
Realtek2super - 05.09.2021 14:19

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

Ответить
Sumon Ahmed
Sumon Ahmed - 05.09.2021 13:31

First.

Ответить
JOHNWHO
JOHNWHO - 05.09.2021 12:42

Chief thank you for the dark theme as well.

Ответить
Tamim Ikbal
Tamim Ikbal - 05.09.2021 12:39

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😍

Ответить
Bumble Bity
Bumble Bity - 05.09.2021 12:24

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

Ответить
Ali Al Qahtani
Ali Al Qahtani - 05.09.2021 11:45

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;

Ответить
ward
ward - 05.09.2021 10:19

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.

Ответить
Tobias Olsson
Tobias Olsson - 05.09.2021 10:07

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.

Ответить
Stefan Kress
Stefan Kress - 05.09.2021 09:49

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

Ответить
h alzagh
h alzagh - 05.09.2021 09:48

thanks very interesting

Ответить