+2

Laravel 5x Shopping cart (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 using dropzonejs Phần 5: Back-end : Tích hợp CKEditor, CKFinder cho bài viết Phần 6: Giới thiệu package ShoppingCart, Installation, Config... Phần 7: Tạo giỏ hàng Phần 8: Tạo & Quản lý đơn hàng...

Phần 8 sẽ có 2 phần, bài này mình sẽ hướng dẫn tạo đơn hàng, bài sau sẽ làm phần (back-end): Nói qua 1 chút, Ở bài trước mình đã hướng dẫn tạo trang giỏ hàng khi người dùng Click btn [tiếp tục] sẽ chuyển đến trang đặt hàng sau , và khi click [Gửi đơn hàng] thì sẽ submit form và lưu thông tin vào db.

Ok, đầu tiên chúng ta cần tạo tables. để lưu thông tin

I. Create table

  • customers: bảng khách hàng: lưu thông tin như tên, địa chỉ, email, sđt...
  • bills: bảng hóa đơn: lưu thông tin như: customer_id, ngày order, tổng số tiền...
  • bill_details: lưu chi tiết hóa đơn: vd: sản phẩm, số lượng, giá...

Tạo table, run 3 cmd sau:

$ php artisan make:migration create_customers_table --create=customers
$ php artisan make:migration create_bills_table --create=bills
$ php artisan make:migration create_bill_details_table --create=bill_details

Sau khi chạy xong, trong thư mục database/migrations/ sẽ có các file tương ứng. Khai báo column cho từng table. database/migrations/2017_10_26_111625_create_customers_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100);
            $table->string('email', 50);
            $table->string('address', 100);
            $table->integer('phone_number');
            $table->string('note')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

database/migrations/2017_10_26_111657_create_bills_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBillsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('bills', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('customer_id');
            $table->dateTime('date_order');
            $table->double('total');
            $table->string('note')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('bills');
    }
}

database/migrations/2017_10_26_111730_create_bill_details_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBillDetailsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('bill_details', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('bill_id');
            $table->integer('product_id');
            $table->integer('quantily');
            $table->double('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('bill_details');
    }
}

sau Khi khai báo các trường dữ liệu xong, run cmd $ php artisan migrate và kiểm tra db. Như vậy đã tạo xong table.

II. Create Route

Route::get('/checkout', 'CartController@getCheckOut');
Route::post('/checkout', 'CartController@postCheckOut');

III. Create Form

tạo blade teamplate theo đường dẫn: resources/views/layouts/checkout.blade.php nội dung:

@extends('layouts.master_full')
@section('content')
    <section>
        <div class="container">
            <div class="row">
                <form action="{{ url('/checkout') }}" method="post">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <div class="col-sm-12 clearfix">
                    <div class="container">
                        <div class="breadcrumbs">
                            <ol class="breadcrumb">
                                <li><a href="#">Home</a></li>
                                <li class="active">Shopping Cart</li>
                            </ol>
                        </div>
                        <div class="bill-to">
                            <p>Thông tin khách hàng</p>
                                @if(count($errors) >0)
                                    <ul>
                                        @foreach($errors->all() as $error)
                                            <li class="text-danger">{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                @endif
                                <div class="form-one">
                                    <input type="text" name="fullName" value="{{ old('fullName') }}" placeholder="Họ và Tên *">
                                    <input type="text" name="email" value="{{ old('email') }}" placeholder="Email *">
                                    <input type="text" name="address" value="{{ old('address') }}" placeholder="Địa Chỉ *">
                                    <input type="text" name="phoneNumber" value="{{ old('phoneNumber') }}" placeholder="Số điện thoại *">
                                    <p style="color: red; font-size: 14px">(*) Thông tin quý khách phải nhập đầy đủ</p>
                                </div>
                                <div class="form-two">
                                    <textarea name="note" value="{{ old('message') }}"  placeholder="Ghi chú" rows="10"></textarea>
                                </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12">
                    <section id="cart_items">
                        <div class="container">
                            <div class="table-responsive cart_info">
                                <table class="table table-condensed">
                                    <thead>
                                    <tr class="cart_menu">
                                        <td class="image">Ảnh minh họa</td>
                                        <td class="description">Tên sản phẩm</td>
                                        <td class="price">Giá</td>
                                        <td class="quantity">Số lượng</td>
                                        <td class="total">Tổng</td>
                                        <td></td>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @if(count($cart))
                                        @foreach($cart as $item)
                                            <tr>
                                                <td class="cart_product" style="margin: 0px">
                                                    @if($item->options->image_path)
                                                        <img width="100px" height="100px" src="{{ asset($item->options->image_path) }}" alt="" />
                                                    @else
                                                        <img width="100px" height="100px" src="{{ asset('layouts/images') }}/home/product1.jpg" alt="" />
                                                    @endif
                                                </td>
                                                <td class="cart_description">
                                                    <h4><a href="">{{ $item->name }}</a></h4>

                                                    <p>Web ID: {{ $item->id }}</p>
                                                </td>
                                                <td class="cart_price">
                                                    <p>{{ number_format($item->price)}} VNĐ</p>
                                                </td>
                                                <td class="cart_quantity">
                                                    {{ $item->qty }}
                                                </td>
                                                <td class="cart_total">
                                                    <p class="cart_total_price">{{ number_format($item->subtotal)}}
                                                        VNĐ</p>
                                                </td>
                                            </tr>
                                        @endforeach
                                        <tr>
                                            <td colspan="4">&nbsp;
                                            <span>
                                            <a class="btn btn-default update" href="{{ url('/cart')}}">Quay về giỏ
                                                hàng</a>
                                            </span>

                                            </td>
                                            <td colspan="2">
                                                <table class="table table-condensed total-result">
                                                    <tbody>
                                                    <tr>
                                                        <td>Tổng :</td>
                                                        <td><span>{{ $total }} VNĐ</span></td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                        </td>
                                                        <td>
                                                            <button type="submit" class="btn btn-default check_out"
                                                               href="{{ url('checkout')}}">Gửi đơn hàng</button></td>
                                                    </tr>
                                                    </tbody>
                                                </table>
                                            </td>
                                        </tr>
                                    @else
                                        <tr>
                                            <td>You have no items in the shopping cart</td>
                                        </tr>
                                        <tr>
                                            <td colspan="4">&nbsp;
                                                <a class="btn btn-default update" href="{{ url('/')}}">Mua hàng</a>
                                            </td>
                                        </tr>
                                    @endif
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                    <!--/#cart_items-->
                </div>
                </form>
            </div>
        </div>
    </section>
@endsection

IV. Create Controller

Nội dung CartController.php

    public function getCheckOut() {
        $this->data['title'] = 'Check out';
        $this->data['cart'] = Cart::content();
        $this->data['total'] = Cart::total();
        return view('layouts.checkout', $this->data);
    }

    public function postCheckOut(Request $request) {
        $cartInfor = Cart::content();
        // validate
        $rule = [
            'fullName' => 'required',
            'email' => 'required|email',
            'address' => 'required',
            'phoneNumber' => 'required|digits_between:10,12'

        ];
        
        $validator = Validator::make(Input::all(), $rule);
        
        if ($validator->fails()) {
            return redirect('/checkout')
                        ->withErrors($validator)
                        ->withInput();
        }
        
        try {
            // save
            $customer = new Customer;
            $customer->name = Request::get('fullName');
            $customer->email = Request::get('email');
            $customer->address = Request::get('address');
            $customer->phone_number = Request::get('phoneNumber');
            //$customer->note = $request->note;
            $customer->save();

            $bill = new Bill;
            $bill->customer_id = $customer->id;
            $bill->date_order = date('Y-m-d H:i:s');
            $bill->total = str_replace(',', '', Cart::total());
            $bill->note = Request::get('note');
            $bill->save();

            if (count($cartInfor) >0) {
                foreach ($cartInfor as $key => $item) {
                    $billDetail = new BillDetail;
                    $billDetail->bill_id = $bill->id;
                    $billDetail->product_id = $item->id;
                    $billDetail->quantily = $item->qty;
                    $billDetail->price = $item->price;
                    $billDetail->save();
                }
            }
          // del
           Cart::destroy();
            
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

V. Test

Kiểm tra db.

Như vậy là đã insert đơn hàng thành công. Bài viết xin tạm dừng tại đây, hy vọng sẽ giúp ích cho bạn, cảm ơn bạn đã theo dõi 😄


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí