Answer the question
In order to leave comments, you need to log in
Evaluate the validation and updating of product data in the controller?
Hello, in my previous question, I asked how to do form validation correctly. There were tips, redid everything. Please rate. What is right? What can be improved and done differently?
app/Http/Controllers/Admin/ProductsController.php
use App\Http\Requests\ProductsUpdateRequest;
class ProductsController extends Controller
{
public function editRequestProduct(ProductsUpdateRequest $request, int $id)
{
$validated = $request->validated();
$objProducts = Products::find($id);
if(!$objProducts){
return abort('404');
}
$image = ImageDNK::save($request, 'image');
$tab_bg = ImageDNK::save($request, 'tab_bg');
$is_reccomended = $request->has('is_reccomended') ? true : false;
$validated['image'] = $image;
$validated['tab_bg'] = $tab_bg;
$validated['is_reccomended'] = $is_reccomended;
$objProducts->fill($validated);
if(!$objProducts->save()){
return back()->with('error', 'Товар не изменен. Попробуйте ещё раз');
}
$hasCategory = $request->input('product_category') != 0;
if($hasCategory){
$objCatsRels = new CategoriesRelationship();
$objCatsRels = $objCatsRels->create([
'object_id' => $id,
'category_id' => $request->input('product_category'),
]);
}
if($objProducts && (!$hasCategory || $objCatsRels)){
return back()->with('success', trans('messages.products.successUpdated'));
}
return back()->with('error', 'Товар не изменен. Попробуйте ещё раз');
}
}
app/Http/Requests/ProductsUpdateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProductsUpdateRequest extends FormRequest
{
public function rules()
{
return [
'title' => 'required|string|min:4|max:25',
'slug' => array(
'required',
'string',
'min:4',
'max:25',
'regex:/^[a-z0-9а-яё-]+$/u',
//'unique:products',
Rule::unique('products')->ignore($this->id),
),
'excerpt' => 'required|string|min:4|max:100',
'content' => 'required|string|min:4|max:300',
'descrtitle' => 'required|string|min:4|max:100',
'descrtext' => 'required|string|min:4|max:300',
'descr' => 'required|string|min:4|max:300',
'regular_price' => array(
'required',
'regex:/\d+/',
),
'discount' => array(
'required',
'min:0',
'max:100',
'regex:/^\d+(\.\d{1,2})?$/',
),
'image' => 'mimes:jpeg,jpg,png,gif|max:10000',
'tab_bg' => 'mimes:jpeg,jpg,png,gif|max:10000',
'product_description_tab_content' => 'string|max:10000',
'product_ingredients_tab_content' => 'string|max:10000',
'product_usage_tab_content' => 'string|max:10000',
'is_reccomended' => '',
];
}
}
Answer the question
In order to leave comments, you need to log in
1) You are moving correctly, that validation is in requests.
2) Redundant code
$objProducts = Products::find($id);
if(!$objProducts){
return abort('404');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question