'Best Practice for Laravel Validation [closed]
I Create New form request and use this for all CRUD operations
and use $this->getMethod(); to check the different between requests
then I face logical issues
Is all fields that required in store method should be required in update method ?
=> the question here is should the consumer of APIs should sent all keys object to update specific key
If It shouldn't and the keys name sent from APIs is different from the Database table columns name
=> I can't use
update($request()->all());because the key isn't the same as columns name, then I need to loop on all request keys to ignore the key that have null - can be done also by multi-check -
So please what the best practice of that ??
Solution 1:[1]
You can do this with the following approach:
$this->validate(
$request,
[
'YOUR INPUT FIELD NAME' => 'required',
]
);
You can also use $request->validate() since Laravel 5.5+:
$request->validate(
[
'YOUR INPUT FIELD NAME' => 'required',
]
);
Solution 2:[2]
$validator = Validator::make($request->all(), [
'phone' => 'sometimes|max:255',
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'pic_file' => 'sometimes|mimes:jpg,png,jpeg,gif|max:1000',
]);
if ($validator->fails()) {
return redirect('/')->withErrors($validator);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | matiaslauriti |
| Solution 2 | francisco |
