Monday, March 14, 2016

Tạo form contact với Laravel

Hướng dẫn tạo Form Contact đơn giản với Laravel 

0. Chuẩn bị
Laravel + Bảng contact + cấu hình kết nối tới database


CREATE TABLE `tld_contact` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) NOT NULL,
  `content` text,
  `is_read` tinyint(1) NOT NULL DEFAULT '0',
  `fullname` varchar(100) NOT NULL COMMENT 'ho ten nguoi gui lien he',
  `email` varchar(255) NOT NULL,
  `phone_number` varchar(15) DEFAULT NULL,
  `address` varchar(15) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `product_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1. Tạo controller

php artisan make:controller --plain Frontend\ContactController
Hàm này sẽ giúp tạo ra 1 controller:  app\Http\Controllers\Frontend\ContactController.php
Với đầy đủ các hàm có thể tương tác với 1 đối tượng: index, create, store, edit, show, edit, destroy
Ở đây sẽ dùng đến 2 hàm: create & store để xử lý việc hiển thị form contact và xử lý lưu contact vào DB



2. Tạo route

Route::group(['namespace' => 'Frontend'], function()
{
  Route::group(['middleware' => ['web']], function () {
    Route::get('contact',
      ['as' => 'contact', 'uses' => 'ContactController@create']);
    Route::post('contact',
      ['as' => 'contact_store', 'uses' => 'ContactController@store']);
  });

});
Tôi tạo 2 route để xử lý việc hiển thị form Contact và xử lý Contact do người dùng đẩy lên.

3. Tạo giao diện form & gán giao diện cho Controller @create
Sửa file: ContactController.php

public function create()
{
 return view('frontend.contact.create', []);
}
- Tạo file giao diện: resources\views\frontend\contact\create.blade.php 
(File layout các bạn tự tạo riêng nhé)
@extends('frontend.layouts.master')
@section('title', trans('frontend.home'))

@section('content')

    <h1>Contact Us</h1>

    @if(Session::has('message'))
        <div class="alert alert-info">
            {{Session::get('message')}}
        </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 method="post" action="{{ route('contact_store', [], false) }}" class="form">
        {!! csrf_field() !!}
        <div class="form-group">
            <label>{{ trans('frontend.Name') }}</label>
            <input type="text" name="fullname" value="{{ old('fullname') }}" required class="form-control" placeholder="Your name" />

        </div>
        <div class="form-group">
            <label>Email </label>
            <input type="text" name="email" value="{{ old('email') }}" required class="form-control email" placeholder="Email" />

        </div>
        <div class="form-group">
            <label>Message</label>
            <textarea type="text" name="content" required class="form-control" placeholder="Your message" >{{ Request::old('content') }}</textarea>
        </div>
        <div class="form-group">
            <input type="submit" value="Contact Us" class="btn btn-primary" />
        </div>
    </form>

@endsection
Note: 

  • {!! csrf_field() !!} --> add token ẩn vào form để chống lỗi CSRF
  • {{ Request::old('content') }} --> hiển thị giá trị trước đó, trong trường hợp validate form lỗi. 
4. Tạo Eloquent Model Contact 

php artisan make:model Models\Contact
Hoặc tự tạo bằng tay với nội dung sau:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
  protected $table = 'contact'; // Ten bang= prefix_ + contact 
  public $timestamps = true;

  protected $fillable = array('fullname', 'email', 'content');
}

5. Khai báo Class Form Contact 
Có vài cách để xử lý với Form, ở đây mình dùng Request Class Form vì nó tường minh hơn
a. Tạo Form: 

php artisan make:request Frontend\ContactFormRequest
b. Nội dung Form

<?php

namespace App\Http\Requests\Frontend;

use App\Http\Requests\Request;

class ContactFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // false --> return Forbidden error
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'fullname' => 'required|max:10',
          'email' => 'required|email',
          'content' => 'required',
        ];
    }
}

6. Xử lý lưu Contact người dùng trong Controller 
Sửa file:  ContactController.php

public function store(ContactFormRequest $request)
{
 $this->validate($request, $request->rules());
 
 // Luu contact 
 $contact = new Contact();
 $input = $request->only(['fullname', 'email', 'content']);
 $contact->create($input);
 
 // Gan message thong bao thanh cong 
 $request->session()->flash('message', 'Thanks for contacting us!');

 return \Redirect::route('contact');
}
7. Test  


hoclaravel.com

6 comments:

  1. Chào ad, mình hiện đang làm project với laravel 5, không biết ad có thể hướng dẫn mình tạo phần gửi thông tin khi có người đăng ký về email được không? mình có làm theo trên mạng nhưng không hoạt động, mong ad hướng dẫn. Cảm ơn ad

    ReplyDelete
  2. Chào bạn Dio Tank LK,
    Thực ra phần forward tin về email, trên mạng họ hướng dẫn đúng cả. Việc không hoạt động có thể do các nguyên nhân sau:
    1. Server của bạn không kết nối được đến mail server
    2. Nếu bạn mua hosting, nhiều khả năng họ đã disable hàm gửi mail để hạn chế việc gửi mail nặc danh --> Bạn nên nhớ bên hosting hỗ trợ.

    Nếu có thể, bạn vui lòng cung cấp thêm 1 số thông tin:
    - Hosting/ server bạn đang mua là ở đâu?
    - Log lỗi khi bạn gửi mail

    ReplyDelete
  3. Chào bạn Dio Tank LK,
    Thực ra phần forward tin về email, trên mạng họ hướng dẫn đúng cả. Việc không hoạt động có thể do các nguyên nhân sau:
    1. Server của bạn không kết nối được đến mail server
    2. Nếu bạn mua hosting, nhiều khả năng họ đã disable hàm gửi mail để hạn chế việc gửi mail nặc danh --> Bạn nên nhớ bên hosting hỗ trợ.

    Nếu có thể, bạn vui lòng cung cấp thêm 1 số thông tin:
    - Hosting/ server bạn đang mua là ở đâu?
    - Log lỗi khi bạn gửi mail

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Chào Admin , Mình muốn làm 1 cái thống kế số khách đang trực tuyến và đếm số người đã ghé thăm trang bằng Laravel 5.2 xin giúp đỡ . Thanks

    ReplyDelete
    Replies
    1. Chào Sa Na,
      Hiện nay các site không còn hiển thị các thông tin như vậy nữa!
      Còn nếu bạn vẫn muốn làm thì có thể tìm các đoạn code PHP share trên mạng khá nhiều, ví dụ từ khóa "PHP count visitors", "PHP simple visitors counter", ..

      Khi code vào Laravel thì bạn chỉ cần lưu ý việc để code đó ở đâu thôi, chứ ko có gì khác biệt nhiều.

      Bạn tham khảo cách viết một cái View Composer, phần lõi bên trong thì bạn paste code thống kê vào là ok thôi.

      http://www.hoclaravel.com/2015/02/huong-dan-tao-view-composer-on-gian-voi.html

      Delete