Create an E-Commerce website with laravel 5x (P3)
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 ...
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 IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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 IlluminateDatabaseEloquentModel; class Category extends Model { protected $table = 'categories'; protected $fillable = [ 'name', 'parent_id' ]; }
Step 2: Create Route
Routesweb.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 AppHttpControllersAdmin; use IlluminateHttpRequest; use AppHttpControllersController; use IlluminateSupportFacadesDB; use IlluminateSupportFacadesInput; use IlluminateSupportFacadesValidator; use IlluminateSupportFacadesRedirect; use IlluminateSupportFacadesSession; use AppCategory; class AdminCategoryController extends Controller { /** * Display a listing of the resource. * * @return IlluminateHttpResponse */ 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 IlluminateHttpResponse */ 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 IlluminateHttpRequest $request * @return IlluminateHttpResponse */ 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 IlluminateHttpResponse */ 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 IlluminateHttpRequest $request * @param int $id * @return IlluminateHttpResponse */ 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 IlluminateHttpResponse */ 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=