Bài 10: Validate Sản Phẩm

Bài 10: Validate Sản Phẩm

 

-    Vào terminal : php artisan make:request ProductAddRequest
-    Vào AdminProductController.php
<?php

namespace App\Http\Controllers;

use App\Category;
use App\Components\Recusive;
use App\Http\Requests\ProductAddRequest;
use App\Product;
use App\ProductImage;
use App\ProductTag;
use App\Tag;
use App\Traits\StorageImageTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Storage;

class AdminProductController extends Controller
{
use StorageImageTrait;
private $category;
private $product;
private $productImage;
private $tag;
private $productTag;
public function __construct(Category $category,Product $product ,ProductImage $productImage,
Tag $tag,ProductTag $productTag)
{
$this->category = $category;
$this->product = $product;
$this->productImage = $productImage;
$this->tag = $tag;
$this->productTag = $productTag;
}

public function index()
{
$products = $this->product->latest()->paginate(5);
return view('admin.product.index', compact('products'));
}
public function create()
{
$htmlOption = $this->getCategory($parentId='');
return view('admin.product.add',compact('htmlOption'));
}
public function getCategory($parentId)
{
$data = $this->category->all();
$recusive = new Recusive($data);
$htmlOption = $recusive->categoryRecusive($parentId);
return $htmlOption;
}
public function store(ProductAddRequest $request)
{
try {
DB::beginTransaction();
$dataProductCreate = [
'name'=>$request->name,
'price' =>$request->price,
'content' => $request->contents,
'user_id' => auth()->id(),
'category_id'=>$request->category_id
];
$dataUploadFeatureImage = $this->storageTraitUpload($request, 'feature_image_path','product');
if (!empty($dataUploadFeatureImage)){
$dataProductCreate['feature_image_name']=$dataUploadFeatureImage['file_name'];
$dataProductCreate['feature_image_path']=$dataUploadFeatureImage['file_path'];
}
$product = $this->product->create($dataProductCreate);

//Insert data -> product_images
if ( $request->hasFile('image_path') ) {
foreach ($request->image_path as $fileItem){
$dataProductImageDetall = $this->storageTraitUploadMutiple($fileItem,'`product_images');
$product->images()->create([
'image_path'=> $dataProductImageDetall['file_path'],
'image_name'=> $dataProductImageDetall['file_name']
]);
}
}
//Insert tags -> product
if (!empty($request->tags)){
foreach ($request->tags as $tagItem){
//Insert to Tags
$tagInstance = $this->tag->firstOrCreate(['name' => $tagItem]);
$tagIds[] = $tagInstance->id;
}
}
$product->tags()->attach($tagIds);
DB::commit();
return redirect()->route('product.index');
} catch (\Exception $exception){
DB::rollBack();
log::error('Message: ' .$exception->getMessage().' --- Line : '.$exception->getLine());
}
}
public function edit($id){
$product = $this->product->find($id);
$htmlOption = $this->getCategory($product->category_id);
return view('admin.product.edit',compact('htmlOption', 'product'));
}
public function update(Request $request,$id)
{
try {
DB::beginTransaction();
$dataProductUpdate = [
'name'=>$request->name,
'price' =>$request->price,
'content' => $request->contents,
'user_id' => auth()->id(),
'category_id'=>$request->category_id
];
$dataUploadFeatureImage = $this->storageTraitUpload($request, 'feature_image_path','product');
if (!empty($dataUploadFeatureImage)){
$dataProductUpdate['feature_image_name']=$dataUploadFeatureImage['file_name'];
$dataProductUpdate['feature_image_path']=$dataUploadFeatureImage['file_path'];
}
$this->product->find($id)->update($dataProductUpdate);
$product = $this->product->find($id);

//Insert data -> product_images
if ( $request->hasFile('image_path') ) {
$this->productImage->where('product_id',$id)->delete();
foreach ($request->image_path as $fileItem){
$dataProductImageDetall = $this->storageTraitUploadMutiple($fileItem,'`product_images');
$product->images()->create([
'image_path'=> $dataProductImageDetall['file_path'],
'image_name'=> $dataProductImageDetall['file_name']
]);
}
}
//Insert tags -> product
if (!empty($request->tags)){
foreach ($request->tags as $tagItem){
//Insert to Tags
$tagInstance = $this->tag->firstOrCreate(['name' => $tagItem]);
$tagIds[] = $tagInstance->id;
}
}
$product->tags()->sync($tagIds);
DB::commit();
return redirect()->route('product.index');
} catch (\Exception $exception){
DB::rollBack();
log::error('Message: ' .$exception->getMessage().' --- Line : '.$exception->getLine());
}
}

public function delete($id){
try {
$this->product->find($id)->delete();
return response()->json([
'code' => 200,
'message' => 'success'
], 200);
}catch (\Exception $exception){
log::error('Message: ' .$exception->getMessage().' --- Line : '.$exception->getLine());
return response()->json([
'code' => 500,
'message' => 'fail'
], 500);
}
}
}
 -    Vào ProductAddRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductAddRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'bail|required|unique:products|max:255|min:5',
'price'=>'required',
'category_id'=>'required',
'contents'=>'required'
];
}
public function messages()
{
return [
'name.required' => 'Tên không được phép đ trng',
'name.unique' => 'Tên không được phép trùng',
'name.max' => 'Tên không được phép vượt quá 255 ký t',
'name.min' => 'Tên không được phép dưới 5 ký t',
'price.required' => 'Giá không được đ trng',
'category_id.required' => 'Danh mc không được đ trng',
'contents.required' => 'Ni dung không được đ trng',
];
}
}

Vào resources => views => admin => product => add.blade.php
<!-- Stored in resources/views/child.blade.php -->

@extends('layouts.admin')

@section('title')
<title>Add product</title>
@endsection

@section('css')
<link href="{{ asset('vendors/select2/select2.min.css') }}" rel="stylesheet" />
<link href="{{ asset('admins/product/add/add.css') }}" rel="stylesheet" />
@endsection

@section('content')
<div class="content-wrapper">
@include('partials.content-header',['name'=>'product', 'key'=>'Add']);

<form action="{{ route("product.store") }}" method="post" enctype="multipart/form-data">
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">

@csrf
<div class="form-group">
<label>Tên sn phm</label>
<input class="form-control @error('name') is-invalid @enderror"
name="name"
placeholder="Nhp tên sn phm"
value="{{old('name')}}"
>
@error('name')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>

<div class="form-group">
<label>Tên giá sn phm</label>
<input type="text"
class="form-control @error('price') is-invalid @enderror"
name="price"
placeholder="Nhp giá sn phm"
value="{{old('price')}}"
>
@error('price')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>

<div class="form-group">
<label>nh đi din</label>
<input type="file"
class="form-control-file"
name="feature_image_path">
</div>

<div class="form-group">
<label>nh chi tiết</label>
<input type="file"
multiple
class="form-control-file"
name="image_path[]">
</div>

<div class="form-group">
<label>Chn danh mc</label>
<select class="form-control select2_init @error('category_id') is-invalid @enderror"
name="category_id">
<option value="">Chn danh mc</option>
{!! $htmlOption !!}}
</select>
@error('category_id')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>

<div class="form-group">
<label>Nhp tag cho sn phm</label>
<select name="tags[]" class="form-control tags_select_choose" multiple="multiple">
</select>

</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label >Nhp ni dung</label>
<textarea
name="contents"
class="form-control
tinymce_editor_init
@error('contents') is-invalid @enderror"
rows="10"
>
{{old('contents')}}
</textarea>
@error('contents')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
</div>
</form>
@endsection

@section('js')
<script src="{{ asset('vendors/select2/select2.min.js') }}"></script>
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script src="{{ asset('admins/product/add/add.js') }}"></script>
@endsection
-    Giải thích value="{{old('name')}}" là giữ lại giá trị vừa nhập.
-    Vào public => admins => product => add.css
.select2-selection__choice{
background-color: #0e2401 !important;
}
.
image_detail_product, .feature_image{
width: 100%;
height: 130px;
object-fit: cover;
}
.
container_image_detail,.feature_image_container{
margin-top: 20px;
}
.alert-danger{
margin-top: 10px;
padding: 3px 5px;
}


-    kết quả khi submit form vi phạm các lỗi

Đăng nhận xét

0 Nhận xét

myadcash