Create an E-Commerce website with laravel 5x (P3)
Bài đăng này đã không được cập nhật trong 3 năm
Tiếp tục SERIES: Tìm hiểu laravel & Xây dựng website bán hàng cùng Laravel 5x.
Phần 1: Blade template, Xây dựng giao diện người dùng Phần 2: User Authentication, Xây dựng trang login Phần 3: Back-end : Category management Phần 4: Back-end : Product management, Upload multiple images
Phần N: Show sp, tạo giỏ hàng, quản lý đơn hàng, Mail....
Ở bài trước (P2) chúng ta đã xây dựng trang login, Trong bài hôm nay mình sẽ tiếp tục xây dựng phần Back-end: Category management
Step 1: Create Category Table and Model
Tạo Table Category, cú pháp:
$ php artisan make:migration create_categories_table --create=categories
Khi đã tạo thành công, mở file vừa tạo, thêm nội dung như sau:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id');
$table->string('name');
$table->string('desc');
$table->string('slug');
$table->string('meta_title');
$table->string('meta_keywords');
$table->string('meta_description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Để table Categories được tạo, bạn cần thực thi câu lệnh sau, và xem kết quả:
$ php artisan migrate
Tạo Category Model
$ php artisan make:model Category
Nội dung file Category
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'name', 'parent_id'
];
}
Step 2: Create Route
Routes\web.php
Route::resource('category', 'AdminCategoryController');
Step 3: Create AdminCategoryController
Cú pháp:
$ php artisan make:controller Admin/AdminCategoryController --resource
Nội dung file AdminCategoryController
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use App\Category;
class AdminCategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->data['title'] = 'List category';
$listCate = DB::table('categories')
->orderBy('id', 'desc')
->paginate(10);//phan trang
$this->data['listCate'] = $listCate;
return view('admin.category.index', $this->data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->data['title'] = "Add Category";
$listCate = DB::table('categories')
->orderBy('id','desc')->get();
$this->data['listCate'] = $listCate;
return view('admin.category.create', $this->data);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rule = [
'txtName' => 'required'
];
$validator = Validator::make(Input::all(), $rule);
if ($validator->fails())
{
return Redirect::to('admincp/category/create')
->withErrors($validator);
} else {
$category = new Category;
$category->name = Input::get('txtName');
$category->slug = Input::get('txtSlug');
$category->desc = Input::get('txtDesc');
$category->parent_id = Input::get('parent_id');
$category->meta_title = Input::get('meta_title');
$category->meta_keywords = Input::get('meta_keywords');
$category->meta_description = Input::get('meta_description');
$category->save();
Session::flash('message', "Successfully created category");
return Redirect::to('admincp/category');
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$category = Category::find($id);
$this->data['title'] = 'Edit Category';
$this->data['category'] = $category;
$this->data['listCate'] = DB::table('categories')
->orderBy('id', 'desc')
->get();
return view('admin.category.edit', $this->data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$rule = [
'txtName' => 'required'
];
$validator = Validator::make(Input::all(), $rule);
if ($validator->fails())
{
return Redirect::to('admincp/category/' . $id . '/edit')
->withErrors($validator);
} else {
$category = Category::find($id);
$category->name = Input::get('txtName');
$category->slug = Input::get('txtSlug');
$category->desc = Input::get('txtDesc');
$category->parent_id = Input::get('parent_id');
$category->meta_title = Input::get('meta_title');
$category->meta_keywords = Input::get('meta_keywords');
$category->meta_description = Input::get('meta_description');
$category->save();
Session::flash('message', "Successfully edited category");
return Redirect::to('admincp/category');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
Session::flash('message', "Successfully delete category");
return Redirect::to('admincp/category');
}
}
Step 4: Create View
Tạo các file trong folder như hình minh họa.
file index.blade.php
<?php
/**
* Created by PhpStorm.
* User: vu.huy.tuan
* Date: 5/26/2017
* Time: 4:18 PM
*/
?>
@extends('admin.master')
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Categories
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Admin</a></li>
<li><a href="#">Categories</a></li>
<li class="active">List</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<a href="{{ url('admincp/category/create') }}" class="btn btn-success">
<i class="fa fa-plus"></i>
<span>Add Category</span>
</a>
<p style="height: 5px"></p>
@if (Session::has('message'))
<div class="alert alert-info"> {{ Session::get('message') }}</div>
@endif
<input type="text" id="myInput" onkeyup="searchByColumnNo('1')" placeholder="Search for names.." class="form-control">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<div class="row">
<div class="col-sm-12">
<table id="myTable" class="table table-bordered table-hover dataTable" role="grid" aria-describedby="example2_info">
<thead>
<tr role="row">
<th class="sorting" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-label="">ID</th>
<th class="sorting_asc" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-sort="ascending" aria-label="">Name</th>
<th class="sorting" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-label="">Slug</th>
<th class="sorting" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-label="">Actions</th></tr>
</thead>
<tbody>
@if (isset($listCate) && count($listCate) >0)
@foreach($listCate as $cate)
<tr role="row" class="odd">
<td>{{ $cate->id }}</td>
<td class="sorting_1">{{ $cate->name }}</td>
<td>{{ $cate->slug }}</td>
<td>
<div class="btn-group">
<a href="{{ url('admincp/category')}}/{{ $cate->id }}/edit" class="btn btn-default bg-purple">
<i class="fa fa-edit"></i>
<span>Edits</span>
</a>
<!--<a href="#" class="btn btn-default bg-red" onclick="delUser('{{ $cate->id }}');"></a>-->
<a href="#" class="btn btn-default bg-red btnDelete" data-value="{{ $cate->id }}">
<i class="fa fa-edit"></i>
<span>Delete</span>
</a>
</div>
</td>
</tr>
@endforeach
@endif
</tbody>
</table>
<div style="float:right">
{!! $listCate->render() !!}
</div>
</div>
</div>
</div>
</div>
<!-- /.box -->
</section>
<!-- /.content -->
<form action="" method="post" id="formDelete">
<input type="hidden" name="_method" value="DELETE">
{{ csrf_field() }}
</form>
<div id="confirm" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirm delete</h4>
</div>
<div class="modal-body">
<p> Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>
<button type="button" data-dismiss="modal" class="btn">Cancel</button>
</div>
</div>
</div>
</div>
@endsection
@section('page-js-script')
<script type="text/javascript">
$(document).ready(function() {
$('.btnDelete').click(function(){
var userId = $(this).attr('data-value');
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '#delete', function (e) {
//delete function
var actionLink = "{{ url('admincp/category')}}/"+ userId;
$('#formDelete').attr('action', actionLink).submit();
});
});
});
</script>
@endsection
create.blade.php
@extends('admin.master')
@section('content')
<section class="content-header">
<h1>
Add Category
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="#">Category</a></li>
<li class="active">Add</li>
</ol>
</section>
<section class="content">
<form action="{{ url('admincp/category') }}" method="POST">
{{ csrf_field() }}
@if(count($errors) >0)
<ul>
@foreach($errors->all() as $error)
<li class="text-danger">{{ $error }}</li>
@endforeach
</ul>
@endif
<div class="box">
<div class="box-body row">
<div class="form-group col-md-12">
<label>Name</label>
<input type="text" name="txtName" class="form-control" value="{{ old('txtName') }}">
</div>
<div class="form-group col-md-12">
<label>Slug</label>
<input type="text" name="txtSlug" class="form-control" value="{{ old('txtSlug') }}">
</div>
<div class="form-group col-md-12">
<label>Desc</label>
<textarea name="txtDesc" class="form-control">{{ old('txtDesc') }}</textarea>
</div>
<div class="form-group col-md-12">
<label>Category</label>
<select class="form-control" name="parent_id" value="{{ old('parent_id') }}">
<option value="0">---</option>
@foreach($listCate as $cate)
<option value="{{ $cate->id }}">{{ $cate->name }}</option>
@endforeach
</select>
</div>
<div class="form-group col-md-12">
<fieldset> <legend>SEO:</legend>
SEO Title <input type="text" name="meta_title" class="form-control" value="{{ old('meta_title') }}">
Meta Keywords <input type="text" name="meta_keywords" class="form-control" value="{{ old('meta_keywords') }}">
Meta Description <input type="text" name="meta_description" class="form-control" value="{{ old('meta_description') }}">
</fieldset>
</div>
</div>
<div class="box-footer row">
<button type="submit" class="btn btn-success">
<i class="fa fa-save"></i>
<span>Save and back</span>
</button>
</div>
</div>
</form>
</section>
@endsection
edit.blade.php
@extends('admin.master')
@section('content')
<section class="content-header">
<h1>
Edit Category
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="#">Category</a></li>
<li class="active">Edit</li>
</ol>
</section>
<section class="content">
<form action="{{ url('admincp/category') }}/{{ $category->id }}" method="POST">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
@if(count($errors) >0)
<ul>
@foreach($errors->all() as $error)
<li class="text-danger">{{ $error }}</li>
@endforeach
</ul>
@endif
<div class="box">
<div class="box-body row">
<div class="form-group col-md-12">
<label>Name</label>
<input type="text" name="txtName" class="form-control" value="{{ $category->name }}">
</div>
<div class="form-group col-md-12">
<label>Slug</label>
<input type="text" name="txtSlug" class="form-control" value="{{ $category->slug }}">
</div>
<div class="form-group col-md-12">
<label>Desc</label>
<textarea name="txtDesc" class="form-control">{{ $category->desc }}</textarea>
</div>
<div class="form-group col-md-12">
<label>Category</label>
<select class="form-control" name="parent_id">
<option value="0">---</option>
@foreach($listCate as $cate)
<option value="{{ $cate->id }}"
@if ($cate->parent_id == $category->parent_id)
selected="selected"
@endif
>{{ $cate->name }}</option>
@endforeach
</select>
</div>
<div class="form-group col-md-12">
<fieldset> <legend>SEO:</legend>
SEO Title <input type="text" name="meta_title" class="form-control" value="{{ $category->meta_title }}">
Meta Keywords <input type="text" name="meta_keywords" class="form-control" value="{{ $category->meta_keywords }}">
Meta Description <input type="text" name="meta_description" class="form-control" value="{{ $category->meta_description }}">
</fieldset>
</div>
</div>
<div class="box-footer row">
<button type="submit" class="btn btn-success">
<i class="fa fa-save"></i>
<span>Save and back</span>
</button>
</div>
</div>
</form>
</section>
@endsection
Test
Ok, như vậy mình đã hướng dẫn xong phần ql danh mục sản phẩm, Cám ơn bạn đã đọc, và theo dõi
All rights reserved