- Vào web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/admin', 'AdminController@loginAdmin');
Route::post('/admin', 'AdminController@postloginAdmin');
Route::get('/home', function () {
return view('home');
});
Route::prefix('admin')->group(function () {
Route::prefix('categories')->group(function () {
Route::get('/',[
'as'=> 'categories.index',
'uses' => 'CategoryController@index'
]);
Route::get('/create',[
'as'=> 'categories.create',
'uses' => 'CategoryController@create'
]);
Route::post('/store',[
'as'=> 'categories.store',
'uses' => 'CategoryController@store'
]);
Route::get('/edit/{id}',[
'as'=> 'categories.edit',
'uses' => 'CategoryController@edit'
]);
Route::post('/update/{id}',[
'as'=> 'categories.update',
'uses' => 'CategoryController@update'
]);
Route::get('/delete/{id}',[
'as'=> 'categories.delete',
'uses' => 'CategoryController@delete'
]);
});
Route::prefix('menus')->group(function () {
Route::get('/',[
'as'=> 'menus.index',
'uses' => 'MenuController@index'
]);
Route::get('/create',[
'as'=> 'menus.create',
'uses' => 'MenuController@create'
]);
Route::post('/store',[
'as'=> 'menus.store',
'uses' => 'MenuController@store'
]);
Route::get('/edit/{id}',[
'as'=> 'menus.edit',
'uses' => 'MenuController@edit'
]);
Route::post('/update/{id}',[
'as'=> 'menus.update',
'uses' => 'MenuController@update'
]);
Route::get('/delete/{id}',[
'as'=> 'menus.delete',
'uses' => 'MenuController@delete'
]);
});
//Product
Route::prefix('product')->group(function () {
Route::get('/',[
'as'=> 'product.index',
'uses' => 'AdminProductController@index',
]);
Route::get('/create',[
'as'=> 'product.create',
'uses' => 'AdminProductController@create',
]);
Route::post('/store',[
'as'=> 'product.store',
'uses' => 'AdminProductController@store'
]);
Route::get('/edit/{id}',[
'as'=> 'product.edit',
'uses' => 'AdminProductController@edit',
]);
Route::post('/update/{id}',[
'as'=> 'product.update',
'uses' => 'AdminProductController@edit',
]);
Route::get('/delete/{id}',[
'as'=> 'product.delete',
'uses' => 'AdminProductController@delete',
]);
});
});
- Vào AdminproductController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Components\Recusive;
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(Request $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 Views => admin => product => index.blade.php
<!-- Stored in resources/views/child.blade.php -->
@extends('layouts.admin')
@section('title')
<title>Add Product</title>
@endsection
@section('css')
<link rel="stylesheet" href="{{ asset('admins/product/index/list.css') }}">
@endsection
@section('js')
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="{{ asset('admins/product/index/list.js') }}"></script>
@endsection
@section('content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
@include('partials.content-header',['name'=>'product', 'key'=>'List']);
<!-- /.content-header -->
<!-- Main content -->
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<a href="{{ route('product.create') }}" class="btn btn-success float-right mr-2">add</a>
</div>
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Tên sản phẩm</th>
<th scope="col">Giá</th>
<th scope="col">Hình ảnh</th>
<th scope="col">Danh mục</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach($products as $productItem)
<tr>
<th scope="row">{{ $productItem->id }}</th>
<td>{{ $productItem->name}} </td>
<td>{{ number_format($productItem->price) }}</td>
<td>
<img class="product_image" src="{{$productItem->feature_image_path}}" alt="">
</td>
<td>{{ optional($productItem->category)->name }}</td>
<td>
<a href="{{ route('product.edit', ['id'=>$productItem->id]) }}"
class="btn btn-default">Edit</a>
<a href=""
data-url="{{ route('product.delete',['id'=>$productItem->id]) }}"
class="btn btn-danger action_delete">Delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="col-md-12">
{{ $products->links() }}
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
@endsection
- Vào Public => admins => tạo foder index => Tạo file list.js
function actionDelete(event){
event.preventDefault();
let urlRequest = $(this).data('url');
let that = $(this);
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
$.ajax({
type:'GET',
url: urlRequest,
success:function (data) {
if (data.code == 200){
that.parent().parent().remove();
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
},
error:function () {
}
})
}
})
}
$(function () {
$(document).on('click','.action_delete',actionDelete);
})
- Vào terminal : php artisan make:migration add_column_delete_at_to_product_table --table=products
- Vào file 2021_07_21_011746_add_column_delete_at_to_product_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddColumnDeleteAtToProductTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
}
- Vào terminal : php artisan migrate
- Vào public => vendors => tạo foder sweetAlert2
- coppy đường đẫn //cdn.jsdelivr.net/npm/sweetalert2@11 lên trình duyệt
- Ctrl+S vào đường dẫn C:\xampp\htdocs\shopping\public\vendors\sweetAlert2
- Vào Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use softDeletes;
protected $guarded = [];
public function images(){
return $this->hasMany(ProductImage::class, 'product_id');
}
public function tags(){
return $this->belongsToMany(Tag::class,'product_tags','product_id','tag_id')
->withTimestamps();
}
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
public function productImages(){
return $this->hasMany(ProductImage::class,'product_id');
}
}

0 Nhận xét