Thứ Tư, 15 tháng 8, 2018

Cách sửa lỗi thêm kí tự "/" vào column có kiểu json khi sử dụng lệnh response()->json

Gỉa sử ta có 1 model là Place được mapping từ table places, table này có feild là place_list_image có kiể dữ liệu là json

Và có 1 PlaceController có 1 function là indexJson dùng để tạo file json có nội dung như sau

public function indexJson(){    $places = Place::all();    $header = array (       'Content-Type' => 'application/json; charset=UTF-8',       'charset' => 'utf-8'    );
      return response()->json(['places' => $places,           'status' => Response::HTTP_OK],200,$header,JSON_UNESCAPED_UNICODE);
}

Khi tạo Json thì trường place_list_image sẽ bị encode 1 lần nữa và sẽ thêm các kí tự "/" vào nộii dung trường place_list_image. Để giải quyết vấn đề này có 2 cách

1. Vào file Model Place ta thêm code sau để chuyển sang array:

protected $casts = [    'place_list_image' => 'array',];

2. Vào file Model Place ta thêm code sau để decode trường place_list_image:

public function getPlaceListImageAttribute($value){    return json_decode($value);}



Thứ Hai, 13 tháng 8, 2018

Tích hợp Bootstrap vào Laravel

SEO (Search Engine Optimization) không còn cái gì mới lạ với các quản trị viên hệ thống website và các lập trình viên ứng dụng web. Trong năm 2015, Google đã từng thông báo các website tuân thủ Responsive sẽ nhận được điểm chất lượng SEO tốt hơn (Response một thuật ngữ ám chỉ website đó có thể hiển thị tương thích trên tất cả các thiết bị với độ phân giải khác nhau). Lý do đơn giản là hiện nay tỉ lệ người dùng sử dụng smart phone, tablet… là khá lớn, nếu giữ website chỉ được thiết kế cho các máy tính cá nhân, các website này sẽ hoạt động không tốt trên các thiết bị thông minh.
Responsive website

Laravel HTML package viết mã HTML dễ dàng

Trong dự án, các tài nguyên như ảnh, các file css, javascript, font… được đặt trong thư mục public, để tổ chức tốt hơn chúng ta sẽ tạo ra các thư mục css, js, font chứa các loại file tương ứng. Khi tham chiếu đến các tài nguyên chúng ta có thể sử dụng ngôn ngữ HTML tiêu chuẩn hoặc có một tùy chọn nữa là sử dụng mã giả của gói Laravel HTML, ví dụ:
<img src="/images/logo.png" alt="All Laravel Logo" />

{!! HTML::image('images/logo.png', 'All Laravel Logo) !!}

Cài đặt gói Laravel HTML package

Đến thư mục gốc của dự án và sử dụng lệnh composer require để cài đặt gói Laravel HTML (tên chính xác là LaravelCollective). Ở các phiên bản Laravel 4.x gói này được cài đặt sẵn trong Laravel nhưng đến phiên bản Laravel 5.x gói này bị loại bỏ, muốn sử dụng phải cài đặt thêm.
c:\xampp\htdocs\laravel-test>composer require laravelcollective/html
Using version ^5.4 for laravelcollective/html
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing laravelcollective/html (v5.4.1): Downloading (100%)
Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled services file has been removed.

Laravel Blade template module hóa trong thiết kế giao diện – Phần 2

Trong phần 1, chúng ta đã cùng nhau tìm hiểu các khái niệm cơ bản Laravel Blade, trong phần 2 này tiếp tục với kiểu cách lập trình trong Blade và cách thức tổ chức Blade template để tận dụng tối đa tính module trong phát triển presentation logic. OK, bắt đầu thôi.

Cấu trúc điều kiện trong Laravel Blade

Mục tiêu của Laravel Blade là để kế thừa và hiển thị dữ liệu, để thực hiện tốt hơn việc này, Laravel Blade cung cấp các lệnh tương tự như trong ngôn ngữ PHP thuần túy như các câu lệnh điều kiện, các vòng lặp…

Câu lệnh điều kiện if

Sử dụng các lệnh @if, @else, @elseif và @endif như trong PHP thuần túy, cú pháp sử dụng như sau:
@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Laravel Blade template module hóa trong thiết kế giao diện – Phần 1

https://allaravel.com/laravel-tutorials/laravel-blade-template-module-hoa-trong-thiet-ke-giao-dien-phan-1/

Laravel Blade là gì?

Mục tiêu chính của mô hình MVC là tách biệt giữa application logic và presentation logic, Laravel cũng vậy nó không muốn ở trong các view có các câu truy vấn hoặc các code không liên quan đến view, và không muốn các Controller, Model quan tâm đến định dạng dữ liệu. Tuy nhiên view cũng cần một số cú pháp đơn giản để đưa các logic vào trong nó, chính vì thế Laravel Blade ra đời. Blade rất đơn giản nhưng là một bộ máy tạo các mẫu web rất mạnh mẽ, không như các bộ máy tạo mẫu khác của PHP, Blade không hạn chế bạn sử dụng các mã PHP thuần túy trong view. Trong thực tế, tất cả các Blade view được biên dịch thành mã PHP thuần túy và được cache cho đến khi chúng có thay đổi. File Blade view có phần mở rộng là .blade.php và thông thường được lưu trong thư mục resources/views.

Kế thừa một template

Các lợi ích của Laravel Blade là kế thừa template và tính năng section, để bắt đầu chúng ta xem một ví dụ đơn giản sau:
Tạo một thư mục layouts trong thư mục resources/views để chứa các template, tiếp theo chúng ta tạo một blade view trong layouts với tên default.blade.php (resources/views/layouts/default.blade.php) có nội dung như sau:
<html>
    <head>
        <title>All Laravel - @yield('title')</title>
    </head>
    <body>

        @section('sidebar')
            Phần chính trong sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>

    </body>
</html>

Laravel view xây dựng logic trong giao diện

https://allaravel.com/laravel-tutorials/laravel-view-xay-dung-logic-trong-giao-dien/

Tìm hiểu về Laravel View

Trong mô hình MVC, V là chữ viết tắt của View. Nó giúp tách biệt giữa application logic và presentation logic giúp quản lý và phát triển mã nguồn tốt hơn. Các view trong Laravel được lưu trữ trong thư mục resources/views. Chúng ta có thể tạo thêm các thư mục trong thư mục resources/views để phân cấp quản lý, trong các ví dụ ở các bài viết trước chúng ta đã tạo thư mục fontend cho tất cả các view liên quan đến fontend, tạo thư mục backend cho các view liên quan đến quản trị. Bạn có thể tạo các thư mục con ở cấp sâu hơn, ví dụ:
  • resources/views/backend/product: Các view liên quan đến quản trị sản phẩm trên website.
  • resources/views/backend/news: Các view liên quan đến quản trị bài viết trên website.
Các view này có thể chứa mã HTML, CSS, Javascript phục vụ cho hiển thị nội dung cho người dùng.

Hướng dẫn Validate form động ở Laravel 5

Nếu bạn đã từng dùng thử hệ thông form validation của Laravel bạn sẽ thấy nó là 1 hệ thống rất mạnh mẽ. Nó làm những công việc quen thuộc, nhàm chán, khó khăn trở lên đơn giản nhưng vẫn hoạt động tốt.
Trong bài viết này tôi muốn chỉ cho các bạn các đơn giản và dễ dàng nhất để validate những form mà có chứa các input động. Trường hợp thông dụng là form mà cho phép user có thể add thêm hay remove các input trong form.
Đây là hình ảnh của 1 form mẫu như vây:
Trong form này khi người dùng click nút "add new" thì sẽ tạo thêm 1 ô textbox nữa, việc này sẽ được xử lý bằng Javascript và nó ngoài phạm vi của bài viết này.
Đây sẽ là phần code PHP demo cho form này
<input type="text" class="form-control" name="name" value="name">

@for ($i=0; $i < 2; $i++)
    <input type="text" name="items[{{ $i }}]" value="{{ $i }}">
@endforeach

Chủ Nhật, 12 tháng 8, 2018

Accessors và Mutators trong Laravel 5.3

https://viblo.asia/p/accessors-va-mutators-trong-laravel-53-rNkKxxjBKlm

Giới thiệu

Có rất nhiều lý do để người dùng lựa chọn sử dụng Eloquent và một trong những lý do đó là Eloquent hỗ trợ Accessors và Mutators. Nếu các bạn chưa nghe đến những cái tên này hay đã nghe qua mà chưa sử dụng thì cũng đừng lo lắng vì nó khá dễ hiểu, nhất là khi đọc qua bài viết của mình 😄 Accessors và Mutators là gì? Nó có nhiệm vụ là cho phép bạn format các attributes của Eloquent khi lấy ra từ một model hoặc là bạn cũng có thể set giá trị cho chúng. Tại sao phải làm vậy? Vì trong project của bạn, 1 thuộc tính có thể sẽ được sử dụng ở rất nhiều nơi, chẳng lẽ mỗi lần sử dụng bạn lại phải format nó. Giờ đây, việc cần làm là truy cập vào Model rồi viết 1 hàm set giá trị cho chúng, sau đó bạn chỉ cần gọi đến tên thuộc tính đó ở mọi nơi. Ví dụ thế này, bạn cần mã hóa mật khẩu cho người dùng khi truy cập vào trang web, thì việc bạn làm đơn giản là băm thuộc tính password rồi sau đó truy xuất nó từ bên trong Eloquent User model. Ngoài việc hỗ trợ tạo accessor và mutator riêng, Eloquent cũng tự động chuyển các trường date thành Carbon instance hoặc thậm chí chuyển trường text thành JSON.

Thứ Bảy, 11 tháng 8, 2018

Truy vấn và cập nhật json column trong Laravel

https://mattstauffer.com/blog/new-json-column-where-and-update-syntax-in-laravel-5-3/

Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.
While Laravel has had the ability to cast your data to and from JSON since version 5.0, it was previously just a convenience—your data was still just stored in a TEXT field. But MySQL 5.7 introduced an actual JSON column type.
Laravel 5.3 introduces a simple syntax for lookups and updates based on the value of specific keys in your JSON columns.

Thứ Sáu, 10 tháng 8, 2018

PHP Laravel 5.6 - Rest API with Passport Tutorial

In this post, I would like to share with you how to create restful API with Passport authentication in laravel 5.6. I will create rest API with passport installation and implementation for authentication from scratch so you can easily understand and use it with your application.
In today's, laravel become more famous PHP framework. almost are prefer laravel for creating API for back-end framework because laravel is the best framework. Laravel provides several features like security, rest API, middleware, passport, events, models, routing etc. it is very easy to use and make it clean code with laravel. a few days ago laravel provide new Laravel 5.6 version in the market.
I also post two tutorial for laravel Rest API and how to use Passport in Laravel application. So you can also follow that tutorial too.
But in this example, i would like to share Rest API with Passport integration in laravel 5.6 application. so if you are new in laravel then i think this tutorial will be best for startup apis and authentication. So you have to just follow few steps and get full example and setup for Rest API.

HOW TO BUILD RESTFUL API USING LAVAVEL 5.6 WITH MYSQL

http://ahex.co/how-to-build-restful-api-using-lavavel-5-6/

In this article we will focus on the following things
1.Basics of RESTful API.
2.Create a new project using laravel 5.6.
3.How to write RESTful APIs.

Laravel 5.6 – REST API – JWT Authentication


https://arjunphp.com/laravel-5-6-rest-api-jwt-authentication/
In my last tutorial, we created an APIs for todo application without authentication. In this tutorial, I would like to show you building JWT based login system. Let’s start…

Thứ Tư, 8 tháng 8, 2018

Xây dựng truy vấn bằng Laravel Query Builder

https://allaravel.com/laravel-tutorials/xay-dung-truy-van-bang-laravel-query-builder/

Truy xuất dữ liệu từ database

Lấy toàn bộ các bản ghi từ một bảng

$users = DB::table('users')->get();
Sử dụng phương thức table() để trả về một instance query builder của một bảng, khi đó muốn lấy tất cả các bản ghi sử dụng phương thức get(). Phương thức get() trả về Illuminate\Support\Collection với mỗi bản ghi là một đối tượng StdClass trong PHP.

Lấy một bản ghi hoặc một cột trong bảng

$user = DB::table('users')->where('name', 'FirebirD')->first();
trả về một bản ghi, còn value() trả về một cột trong bảng
$email = DB::table('users')->where('name', 'FirebirD')->value('email');

Lấy nhiều cột trong bảng

$users = DB::table('users')->pluck('id', 'name');

@foreach ($users as $id => $name)
    {{ $name }} có mã s là {{ $id }}
@endforeach

Lấy giá trị tổng hợp từ kết quả truy vấn

Laravel Query Builder hỗ trợ nhiều các phương thức tổng hợp như sau:
  • min: giá trị nhỏ nhất
  • max: giá trị lớn nhất
  • avg: giá trị trung bình
  • count: tổng số bản ghi
  • sum: lấy tổng một trường nào đó của bảng.
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');

Các phương thức trong query builder

Select

select sử dụng để lựa chọn các cột trong một bảng:
$users = DB::table('users')->select('name', 'email as user_email')->get();
distinct() sử dụng để lọc và trả về các kết quả không bị trùng lặp
$users = DB::table('users')->distinct()->get();

Raw expression

Đôi khi bạn muốn có một thành phần của raw SQL query, có thể sử dụng DB::raw
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Mệnh đề where

Các mệnh đề where đơn giản với điều kiện =, >=, <=, <>, like
$users = DB::table('users')->where('votes', '=', 100)->get();
$users = DB::table('users')
                ->where('name', 'like', '%Kiên%')
                ->get();
Thậm chí có thể truyền một mảng điều kiện vào mệnh đề where
$users = DB::table('users')->where([
    ['active', '=', '1'],
    ['vote', '>', '50'],
    ['name', 'like', '%Kiên%'],
])->get();
Điều kiện trong một câu truy vấn có thể rất phức tạp khi kết hợp các mệnh đề where khác như: orWhere, whereBetween, whereNotBetween, whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereColumn, whereExist. Các ví dụ cho từng kiểu mệnh đề where như sau:
// Ví dụ về orWhere
$users = DB::table('users')
                    ->where('vote', '>', 50)
                    ->orWhere('comment', '>', 50)
                    ->get();
// Ví dụ về whereBetween
$users = DB::table('users')
                    ->whereBetween('age', [18, 35])->get();
// Ví dụ về whereIn
$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();
// Ví dụ về whereNull
$users = DB::table('users')
                    ->whereNull('vote')
                    ->get();
// Ví dụ về whereDate
$users = DB::table('users')
                ->whereDate('join_date', '2017-03-27')
                ->get();
//Ví dụ về whereDay
$users = DB::table('users')
                ->whereDay('join_date', '27')
                ->get();
// Ví dụ về whereMonth
$users = DB::table('users')
                ->whereMonth('join_date', '03')
                ->get();
//Ví dụ về whereYear
$users = DB::table('users')
                ->whereYear('join_date', '2017')
                ->get();
//Ví dụ về whereColumn
$users = DB::table('account')
                ->whereColumn([
                    ['working_balance', '=', 'last_balance'],
                    ['updated_at', '>', 'created_at']
                ])->get();
// Ví dụ về whereExist
DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();
// Ví dụ nhóm các điều kiện trong mệnh đề điều kiện
DB::table('users')
            ->where('name', '=', 'FirebirD')
            ->orWhere(function ($query) {
                $query->where('vote', '>', 50)
                      ->where('role', '<>', 'superadmin');
            })
            ->get();

Thao tác với kết quả trả về

Sắp xếp kết quả trả về của truy vấn bằng phương thức orderBy()
$users = DB::table('users')
                ->orderBy('vote', 'desc')
                ->get();
Lấy ngẫu nhiên một bản ghi
$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
GroupBy và having:
$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();
Insert một hoặc nhiều bản ghi vào CSDL
// Insert một bản ghi
DB::table('users')->insert(
    ['name' => 'Nguyễn Văn A', 'email' => 'anv@gmail.com', 'votes' => 0]
);
// Insert nhiều bản ghi
DB::table('users')->insert([
    ['name' => 'Nguyễn Văn A', 'email' => 'anv@gmail.com', 'votes' => 0],
    ['name' => 'Nguyễn Văn B', 'email' => 'bnv@gmail.com', 'votes' => 0],
    ['name' => 'Nguyễn Văn C', 'email' => 'cnv@gmail.com', 'votes' => 0],
    ['name' => 'Nguyễn Văn D', 'email' => 'dnv@gmail.com', 'votes' => 0],
]);
Có những trường hợp khi insert vào CSDL bạn cần lấy lại ID bản ghi để làm tham số cho các thao tác tiếp theo, sử dụng insertGetId
$user_id = DB::table('users')->insertGetId(
    ['name' => 'Nguyễn Văn A', 'email' => 'anv@gmail.com', 'votes' => 0]
);
echo 'User vừa đăng ký có id là' . $user_id;
Update dữ liệu trong CSDL
Sử dụng phương thức update(), ví dụ:
DB::table('users')
            ->whereYear('join_date', '2017')
            ->orWhere('vote', '>', 50)
            ->update(['generate_promote_code' => 1]);
Delete dữ liệu trong CSDL
DB::table('users')
              ->where('active', '=', 0)
              ->whereYear('join_date', '2015')
              ->delete();
Để xóa toàn bộ các bản ghi trong một bảng và thiết lập ID sinh tự động về 0 sử dụng lệnh truncate()
DB::table('users')->truncate();

Ví dụ sử dụng Laravel Query Builder

Xây dựng một số trang phục vụ các việc sau nhập thông tin sản phẩm, quản lý danh sách sản phẩm: xóa sản phẩm, sửa sản phẩm… Chúng ta cùng bắt đầu thực hiện nào!
Bước 1: Tạo bảng products trong database laravel-test đã tạo trong bài Làm việc với cơ sở dữ liệu trong Laravel.
Bảng products trong ví dụ sử dụng Query Builder trong Laravel
Bước 2: Tạo một controller tên là ProductController, sử dụng Restful Resource Controller.
c:\xampp\htdocs\laravel-test>php artisan make:controller ProductController --res
ource
Controller created successfully.
Bước 3: Thêm resource route vào routes/web.php
Route::resource('product', 'ProductController', ['only' => [
    'create', 'store', 'edit'
]]);
Bước 4: Xử lý từng hành động trên sản phẩm
Bảng route tương ứng cho từng hành động như sau:
VerbURIActionRoute Name
GET/productindexproduct.index
GET/product/createcreateproduct.create
POST/productstoreproduct.store
GET/product/{product_id}showproduct.show
GET/product/{product_id}/editeditproduct.edit
PUT/PATCH/product/{product_id}updateproduct.update
DELETE/product/{product_id}destroyproduct.destroy
Tạo mới sản phẩm:
Tạo view create.blade.php trong resources/views/fontend/product
@extends('layouts.default')

@section('title', 'Tạo sản phẩm')

@section('content')
    @if(isset($success))
  <div class="alert alert-success" role="alert">{{ $success }}</div>
    @endif
    @if(isset($fail))
  <div class="alert alert-danger" role="alert">{{ $fail }}</div>
    @endif

    {!! Form::open(array('url' => '/product', 'class' => 'form-horizontal')) !!}
      <div class="form-group">
         {!! Form::label('name', 'Tên sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::text('name', '', array('class' => 'form-control')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('price', 'Giá sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-3">
            {!! Form::text('price', '', array('class' => 'form-control')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('content', 'Nội dung sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::textarea('content', '', array('class' => 'form-control', 'rows' => 3)) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('image_path', 'Ảnh sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::text('content', '', array('class' => 'form-control')) !!}
         </div>
      </div>
      
      <div class="form-group">
         {!! Form::label('active', 'Active', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-3">
            {!! Form::checkbox('active', '', true) !!}
         </div>
      </div>  

      <div class="form-group">
         <div class="col-sm-offset-2 col-sm-10">
            {!! Form::submit('Tạo sản phẩm', array('class' => 'btn btn-success')) !!}
         </div>
      </div>
   {!! Form::close() !!}
@endsection
Thêm nội dung phương thức create trong ProductController
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('fontend.product.create');
    }
Tiếp đến chúng ta xử lý insert sản phẩm vào CSDL, nó sẽ nằm trong phương thức store của ProductController (xem bảng các route của product)
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'       => 'required|max:255',
            'price'      => 'required|number',
            'content'    => 'required',
            'image_path' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect('product/create')
                    ->withErrors($validator)
                    ->withInput();
        } else {
            // Lưu thông tin vào database, phần này sẽ giới thiệu ở bài về database
            $active = $request->has('active')? 1 : 0;
            $product_id = DB::table('product')->insertGetId(
                'name'       => $request->input('name'),
                'price'      => $request->input('price'),
                'content'    => $request->input('content'),
                'image_path' => $request->input('image_path'),
                'active'     => $active
                );
            return redirect('product/create')
                    ->with('message', 'Sản phẩm được tạo thành công với ID: ' . $product_id);
        }
    }
Để nhập sản phẩm ta vào đường dẫn http://laravel.dev/product/create
Màn hình tạo sản phẩm trong ví dụ sử dụng query builder trong Laravel
Danh sách sản phẩm:
Danh sách sản phẩm sẽ được xử lý trong phương thức index của ProductController, chúng ta thêm nội dung cho phương thức này như sau:
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = DB::table('products')->get();
        return view('fontend.product.list')->with($products);
    }
Tiếp đến chúng ta tạo một view để hiển thị danh sách sản phẩm tên là list.blade.php nằm trong thư mục resources/views/fontend/product
@extends('layouts.default')

@section('title', 'Danh sách sản phẩm')

@section('content')
    <table class="table table-bordered">
        <tr class="success">
            <th>ID</th>
            <th>Tên sn phm</th>
            <th>Giá sn phm</th>
            <th>Ni dung</th>
            <th>nh sn phm</th>
            <th>Đăng bán</th>
            <th>Action</th>
        </tr>
        @foreach($products as $p)
        <tr>
            <td>{{ $p->id }}</td>
            <td>{{ $p->name }}</td>
            <td class="text-right">{{ number_format($p->price) }}</td>
            <td>{{ $p->content }}</td>
            <td>
                <img src="{{ Asset($p->image_path) }}" alt="{{ $p->name }}" width="120" height="120">
            </td>
            <td>
                @if($p->active)
                    <span class="text-success glyphicon glyphicon-ok"></span>
                @else
                    <span class="text-danger glyphicon glyphicon-remove"></span>
                @endif
            </td>
            <td>
                <a href="{{ '/product/' . $p->id . '/edit'}}"><span class="glyphicon glyphicon-pencil">Edit</span></a>
                <a href="{{ '/product/' . $p->id }}"><span class="glyphicon glyphicon-trash">Delete</span></a>
            </td>
        </tr>
        @endforeach
    </table>
@endsection
Kết quả khi chạy http://laravel.dev/product ta có danh sách các sản phẩm
Danh sách sản phẩm trong ví dụ sử dụng query builder trong Laravel
Chỉnh sửa sản phẩm
Chúng ta sử dụng phương thức edit() trong ProductController để chỉnh sửa sản phẩm, nội dung phương thức này như sau:
     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = DB::table('products')->find($id);
        return view('fontend.product.edit')->with(compact('product'));
    }
Tạo một view để chỉnh sửa sản phẩm resources/views/fontend/product/edit.blade.php với nội dung như sau:
@extends('layouts.default')

@section('title', 'Chỉnh sửa sản phẩm')

@section('content')
    @if(isset($success))
  <div class="alert alert-success" role="alert">{{ $success }}</div>
    @endif
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    {!! Form::open(array('url' => '/product/' . $product->id, 'class' => 'form-horizontal', 'method' => 'put')) !!}
      <div class="form-group">
         {!! Form::label('name', 'Tên sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::text('name', $product->name, array('class' => 'form-control')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('price', 'Giá sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-3">
            {!! Form::text('price', $product->price, array('class' => 'form-control')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('content', 'Nội dung sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::textarea('content', $product->content, array('class' => 'form-control', 'rows' => 3)) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('image_path', 'Ảnh sản phẩm', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-9">
            {!! Form::text('image_path', $product->image_path, array('class' => 'form-control')) !!}
         </div>
      </div>
      
      <div class="form-group">
         {!! Form::label('active', 'Active', array('class' => 'col-sm-3 control-label')) !!}
         <div class="col-sm-3">
            {!! Form::checkbox('active', $product->active, true) !!}
         </div>
      </div>  

      <div class="form-group">
         <div class="col-sm-offset-2 col-sm-10">
            {!! Form::submit('Chỉnh sửa sản phẩm', array('class' => 'btn btn-success')) !!}
         </div>
      </div>
   {!! Form::close() !!}
@endsection
Phương thức update() của ProductController đảm nhận phần cập nhật nội dung sản phẩm, thêm code vào phương thức này như sau:
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $active = $request->has('active')? 1 : 0;
        $updated = DB::table('products')
            ->where('id', '=', $id)
            ->update([
                'name'       => $request->input('name'),
                'price'      => $request->input('price'),
                'content'    => $request->input('content'),
                'image_path' => $request->input('image_path'),
                'active'     => $active,
                'updated_at' => \Carbon\Carbon::now()
                ]);
        return Redirect::back()
            ->with('message', 'Cập nhật sản phẩm thành công')
            ->withInput(); 
    }
OK, giờ chúng ta click vào Edit sản phẩm bất kỳ trong danh sách sản phẩm nó sẽ xuất hiện cửa sổ chỉnh sửa sản phẩm
Màn hình chỉnh sửa sản phẩm trong ví dụ sử dụng query builder trong laravel
Thay đổi thông tin và click Chỉnh sửa sản phẩm, sau đó vào lại trang danh sách sản phẩm http://laravel.dev/product chúng ta sẽ thấy nội dung đã thay đổi.
Xóa một sản phẩm
Thông thường các sản phẩm khi đã nhập vào hệ thống chúng ta sẽ không xóa đi mà chỉ cần không active nó lên là ok, do vậy phần này mình bỏ qua nhé, với lại cũng hơi lười tí.

Lời kết

Laravel Query Builder giúp chúng ta xây dựng ứng dụng thật nhanh chóng cho dù các câu truy vấn có phức tạp đến đâu chúng ta cũng xử lý rất dễ dàng. Trong ví dụ phần ảnh sản phẩm tôi tạm thời để theo kiểu copy bằng tay đường dẫn ảnh sản phẩm. Trong thời gian tới, khi nào rảnh tôi sẽ hướng dẫn bạn tích hợp CKEditor và CKFinder vào hệ thống giúp đưa vào nội dung phong phú vào và quản lý lựa chọn tài nguyên như ảnh, file dễ dàng hơn.

Laravel với MongoDB

Mở đầu Hello anh em, đến hẹn lại lên hôm nay mình xin chia sẻ với mọi người về chủ đề Laravel kết hợp với MongoDB mà thông thường ta hay ...