2019年2月27日 星期三

shop2電子商務網站規劃

shop2:

========================
shop2電子商務網站

*shop2電子商務網站規劃
*網址設計規劃
*建立新專案
*建立路由
*建立資料庫

========================
*shop2電子商務網站規劃:

1.情境分析
2.功能需求分析
3.資料表欄位規劃

--------------------
1.情境分析:

*使用者(user)
管理者
消費者

*商品(merchandise)

*交易紀錄(transaction)

--------------------
2.功能需求分析:

*會員:
會員註冊
會員登入身分驗證
註冊Email通知

*商品:
建立商品
上傳商品圖片
商品清單

*交易:
購買商品
交易紀錄清單

*其他:
延遲發送註冊Email通知
發送電子報
多國語言

--------------------
3.資料表欄位規劃:

*使用者(user):
說明, 欄位名稱, 欄位屬性, 備註

會員編號 id integer (primary key, auto increment)
Email email varchar(150) (unique key)
密碼 password varchar(60)
帳號類型 type varchar(1) (A:Admin 管理者)(G:General 一般會員:預設值)
暱稱 nickname varchar(50)
建立時間 created_at datetime
更新時間 updated_at datetime

*商品(merchandise):
說明, 欄位名稱, 欄位屬性, 備註

商品編號 id integer (primary key, auto increment)
商品狀態 status varchar(1) (C:Create 建立中:預設值)(S:Sell 可販售)(視需要可加 D:Discontinued 停產)
商品名稱 name varchar(80)
商品英文名稱 name_en varchar(80)
商品介紹 introduction text
商品英文介紹 introduction_en text
商品照片 photo varchar(50)
商品價格 price integer
商品剩餘數量 remain_count integer
建立時間 created_at datetime
更新時間 updated_at datetime

*交易紀錄(transaction):
說明, 欄位名稱, 欄位屬性, 備註

交易編號 id integer (primary key, auto increment)
使用者編號 user_id integer
商品編號 merchandise_id integer
當時購買單價 price integer
購買數量 buy_count integer
交易總價格 total_price integer
建立時間 created_at datetime
更新時間 updated_at datetime

========================
*網址設計規劃:

*請求路由處理流程:
使用者 => 路由 => 資料處理

--------------------
*網址設計規範:
/資源/{資源編號}/{動作?}

--------------------
*HTTP方法(Method):
動作說明, 方法

檢視 GET
新增 POST
刪除 DELETE
修改 PUT

--------------------
*網址主從關係設計與HTTP方法:
說明, 網址規劃, HTTP方法, controller@functon

首頁 / GET HomeController@indexPage

使用者註冊頁面 /user/auth/sign-up GET UserAuthController@signUpPage
使用者資料新增 /user/auth/sign-up POST UserAuthController@signUpProcess
使用者登入頁面 /user/auth/sign-in GET UserAuthController@signInpage
使用者登入處理 /user/auth/sign-in POST UserAuthController@signInProcess
使用者登出 /user/auth/sign-out GET UserAuthController@signOut

商品清單檢視 /merchandise GET MerchandiseController@merchandiseListPage
商品管理清單檢視 /merchandise/manage GET MerchandiseController@merchandiseManageListPage
商品資料新增 /merchandise/create GET MerchandiseController@merchandiseCreateProcess
商品單品檢視 /merchandise/{merchandise_id} GET MerchandiseController@merchandiseItemPage
商品單品編輯頁面檢視 /merchandise/{merchandise_id}/edit GET MerchandiseController@merchandiseItemEditPage
商品單品資料修改 /merchandise/{merchandise_id} PUT MerchandiseController@merchandiseItemUpdateProcess
購買商品 /merchandise/{merchandise_id}/buy POST MerchandiseController@merchandiseItemBuyProcess

交易記錄頁面檢視 /transaction GET TransactionController@transactionListPage

--------------------
*路由設計:
routes\web.php

// 首頁
Route::get('/', 'MerchandiseController@indexPage');

// 使用者
Route::group(['prefix' => 'user'], function(){
    // 使用者驗證
    Route::group(['prefix' => 'auth'], function(){
        Route::get('/sign-up', 'UserAuthController@signUpPage');
        Route::post('/sign-up', 'UserAuthController@signUpProcess');
        Route::get('/sign-in', 'UserAuthController@signInPage');
        Route::post('/sign-in', 'UserAuthController@signInProcess');
        Route::get('/sign-out', 'UserAuthController@signOut');
        // Facebook 登入
        Route::get('/facebook-sign-in', 'UserAuthController@facebookSignInProcess');
        // Facebook 登入重新導向授權資料處理
        Route::get('/facebook-sign-in-callback', 'UserAuthController@facebookSignInCallbackProcess');
    });
});

// 商品
Route::group(['prefix' => 'merchandise'], function(){
    Route::get('/', 'MerchandiseController@merchandiseListPage');
  
    Route::get('/create', 'MerchandiseController@merchandiseCreateProcess')
        ->middleware(['user.auth.admin']);
    Route::get('/manage', 'MerchandiseController@merchandiseManageListPage')
        ->middleware(['user.auth.admin']);
  
    // 指定商品
    Route::group(['prefix' => '{merchandise_id}'], function(){
        Route::get('/', 'MerchandiseController@merchandiseItemPage')
            ->where([
                'merchandise_id' => '[0-9]+',
            ]);
      
        Route::group(['middleware' => ['user.auth.admin']], function(){
            Route::get('/edit', 'MerchandiseController@merchandiseItemEditPage');
            Route::put('/', 'MerchandiseController@merchandiseItemUpdateProcess');
        });
      
        Route::post('/buy', 'MerchandiseController@merchandiseItemBuyProcess')
            ->middleware(['user.auth']);
    });
});

// 交易
Route::get('/transaction', 'TransactionController@transactionListPage')
    ->middleware(['user.auth']);

========================
*建立新專案:

laravel new shop2

---------------
 *.env的APP_KEY問題:

RuntimeException
No application encryption key has been specified.

解決:
php artisan key:generate

========================
*建立路由:

routes\web.php

*方法1:路由設定(不用路由群組)

//首頁
Route::get('/','HomeController@indexPage');

//使用者
Route::get('/user/auth/sign-up','UserAuthController@signUpPage');
Route::post('/user/auth/sign-up','UserAuthController@signUpProcess');
Route::get('/user/auth/sign-in','UserAuthController@signInpage');
Route::post('/user/auth/sign-in','UserAuthController@signInProcess');
Route::get('/user/auth/sign-out','UserAuthController@signOut');

//商品
Route::get('/merchandise','MerchandiseController@merchandiseListPage');
Route::get('/merchandise/manage','MerchandiseController@merchandiseManageListPage');
Route::get('/merchandise/create','MerchandiseController@merchandiseCreateProcess');
Route::get('/merchandise/{merchandise_id}','MerchandiseController@merchandiseItemPage');
Route::get('/merchandise/{merchandise_id}/edit','MerchandiseController@merchandiseItemEditPage');
Route::put('/merchandise/{merchandise_id}','MerchandiseController@merchandiseItemUpdateProcess');
Route::post('/merchandise/{merchandise_id}/buy','MerchandiseController@merchandiseItemBuyProcess');

//交易
Route::get('/transaction','TransactionController@transactionListPage');

-----------------------------------
*方法2:路由群組設定

// 首頁
Route::get('/', 'MerchandiseController@indexPage');

// 使用者
Route::group(['prefix' => 'user'], function(){
    // 使用者驗證
    Route::group(['prefix' => 'auth'], function(){
        Route::get('/sign-up', 'UserAuthController@signUpPage');
        Route::post('/sign-up', 'UserAuthController@signUpProcess');
        Route::get('/sign-in', 'UserAuthController@signInPage');
        Route::post('/sign-in', 'UserAuthController@signInProcess');
        Route::get('/sign-out', 'UserAuthController@signOut');
        // Facebook 登入
        Route::get('/facebook-sign-in', 'UserAuthController@facebookSignInProcess');
        // Facebook 登入重新導向授權資料處理
        Route::get('/facebook-sign-in-callback', 'UserAuthController@facebookSignInCallbackProcess');
    });
});

// 商品
Route::group(['prefix' => 'merchandise'], function(){
    Route::get('/', 'MerchandiseController@merchandiseListPage');
  
    Route::get('/create', 'MerchandiseController@merchandiseCreateProcess')
        ->middleware(['user.auth.admin']);
    Route::get('/manage', 'MerchandiseController@merchandiseManageListPage')
        ->middleware(['user.auth.admin']);
  
    // 指定商品
    Route::group(['prefix' => '{merchandise_id}'], function(){
        Route::get('/', 'MerchandiseController@merchandiseItemPage')
            ->where([
                'merchandise_id' => '[0-9]+',
            ]);
      
        Route::group(['middleware' => ['user.auth.admin']], function(){
            Route::get('/edit', 'MerchandiseController@merchandiseItemEditPage');
            Route::put('/', 'MerchandiseController@merchandiseItemUpdateProcess');
        });
      
        Route::post('/buy', 'MerchandiseController@merchandiseItemBuyProcess')
            ->middleware(['user.auth']);
    });
});

// 交易
Route::get('/transaction', 'TransactionController@transactionListPage')
    ->middleware(['user.auth']);

========================
*建立資料庫:

1.建立資料庫 shop2
2.設定 .env
3.建立model
4.建立migration
5.設定model
6.設定migration
7.執行migrate

----------------
*model名稱:(資料夾 app\Shop\Entity)
Merchandise
Transaction
User

*migration名稱:
create_users_table
create_merchandise_table
create_transaction_table
add_facebook_id_to_users_table

----------------
*建立model:
在app建立資料夾 Shop\Entity

php artisan make:model Merchandise
php artisan make:model Transaction
php artisan make:model User

----------------
*建立migration:

php artisan make:migration create_users_table
php artisan make:migration create_merchandise_table
php artisan make:migration create_transaction_table
php artisan make:migration add_facebook_id_to_users_table

----------------
*設定model:

*使用者:
app\Shop\Entity\User.php

<?php

namespace App\Shop\Entity;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Model
{
    protected $table = "users";
    protected $primaryKey = "id";
    protected $fillable = [
        "email",
        "password",
        "type",
        "nickname",
    ];
}

*商品:
app\Shop\Entity\Merchandise.php

<?php

namespace App\Shop\Entity;

use Illuminate\Database\Eloquent\Model;

class Merchandise extends Model
{
    protected $table = 'merchandise';
    protected $primaryKey = 'id';
    protected $fillable = [
        "id",
        "status",
        "name",
        "name_en",
        "introduction",
        "introduction_en",
        "photo",
        "price",
        "remain_count",
    ];
}

*交易紀錄:
app\Shop\Entity\Transaction.php

<?php

namespace App\Shop\Entity;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    protected $table = "transaction";
    protected $primaryKey = "id";
    protected $fillable = [
        "id",
        "user_id",
        "merchandise_id",
        "price",
        "buy_count",
        "total_price",
    ];

    //Eloquent:關聯
    public function Merchandise()
    {
        //Transaction的merchandise_id 對應 Merchandise的id
        return $this->hasOne('App\Shop\Entity\Merchandise', 'id', 'merchandise_id');
    }
}

----------------
*設定migration:

*使用者(user):
database\migrations\2014_10_12_000000_create_users_table.php

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    /*
    *使用者(user):
    說明, 欄位名稱, 欄位屬性, 備註

    會員編號 id integer (primary key, auto increment)
    Email email varchar(150) (unique key)
    密碼 password varchar(60)
    帳號類型 type varchar(1) (A:Admin 管理者)(G:General 一般會員:預設值)
    暱稱 nickname varchar(50)
    建立時間 created_at datetime
    更新時間 updated_at datetime
    */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email', 150)->unique();
            $table->string('password', 60);
            $table->string('type', 1)->default('G');
            $table->string('nickname', 50);
            $table->timestamps();
            $table->unique(['email'], 'user_email_uk');
        });
    }

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

*商品(merchandise):
database\migrations\2019_02_26_052053_create_merchandise_table.php

<?php

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

class CreateMerchandiseTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    /*
    *商品(merchandise):
    說明, 欄位名稱, 欄位屬性, 備註

    商品編號 id integer (primary key, auto increment)
    商品狀態 status varchar(1) (C:Create 建立中:預設值)(S:Sell 可販售)(視需要可加 D:Discontinued 停產)
    商品名稱 name varchar(80)
    商品英文名稱 name_en varchar(80)
    商品介紹 introduction text
    商品英文介紹 introduction_en text
    商品照片 photo varchar(50)
    商品價格 price integer
    商品剩餘數量 remain_count integer
    建立時間 created_at datetime
    更新時間 updated_at datetime
    */
    public function up()
    {
        Schema::create('merchandise', function (Blueprint $table) {
            $table->increments('id');
            $table->string('status', 1)->default('C');
            $table->string('name', 80)->nullable();
            $table->string('name_en', 80)->nullable();
            $table->text('introduction');
            $table->text('introduction_en');
            $table->string('photo', 50)->nullable();
            $table->integer('price');
            $table->integer('remain_count_integer');
            $table->timestamps();
            $table->index(['status'], 'merchandise_satus_idx');
        });
    }

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

*交易紀錄(transaction):
database\migrations\2019_02_26_052234_create_transaction_table.php

<?php

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

class CreateTransactionTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    /*
    *交易紀錄(transaction):
    說明, 欄位名稱, 欄位屬性, 備註

    交易編號 id integer (primary key, auto increment)
    使用者編號 user_id integer
    商品編號 merchandise_id integer
    當時購買單價 price integer
    購買數量 buy_count integer
    交易總價格 total_price integer
    建立時間 created_at datetime
    更新時間 updated_at datetime
    */
    public function up()
    {
        Schema::create('transaction', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('merchandise_id');
            $table->integer('price');
            $table->integer('buy_count');
            $table->integer('total_price');
            $table->timestamps();
            $table->index(['user_id'], 'user_transaction_idx');
        });
    }

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

*使用者(user)新增欄位:
database\migrations\2019_02_26_052250_add_facebook_id_to_users_table.php

<?php

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

class AddFacebookIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //加入facebook_id欄位到password欄位後方
            $table->string('facebook_id', 30)
                ->nullable()
                ->after('password');
            $table->index(['facebook_id'], 'user_fb_idx');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //移除欄位
            $table->dropColumn('facebook_id');
        });
    }
}

----------------
*執行migrate:
php artisan migrate

========================
*語系設定:

1.config檔案設定:
config\app.php

'timezone' => 'Asia/Taipei',

'locale' => 'zh-TW',

'fallback_locale' => 'zh-TW',

---------------
2.語系檔案設定:

*英文:
resources\lang\en\shop.php

<?php
// 檔案位置:resources/lang/en/shop.php
return [
    'home'        => 'Home',
    'transaction' => [
        'name'   => 'Transaction',
        'list'   => 'Transaction List',
        'buy'    => 'Buy',
        'fields' => [
            'buy-count' => 'Buy Number',
        ],
    ],
    'merchandise' => [
        'name'             => 'Merchandise',
        'create'           => 'Create Merchandise',
        'manage'           => 'Manage Merchandise',
        'edit'             => 'Edit Merchandise',
        'list'             => 'Merchandise List',
        'page'             => 'Merchandise Page',
        'purchase-success' => 'Purchase Success',
        'update'           => 'Update',
        'fields'           => [
            'id'              => 'Id',
            'status-name'     => 'Status',
            'status'          => [
                'create' => 'Create',
                'sell'   => 'Sell',
            ],
            'name'            => 'Name',
            'name-en'         => 'English Name',
            'introduction'    => 'Introduction',
            'introduction-en' => 'English Introduction',
            'photo'           => 'Photo',
            'price'           => 'Price',
            'remain-count'    => 'Remain Number',
        ],
    ],
    'auth'        => [
        'sign-out'         => 'Sign Out',
        'sign-in'          => 'Sign In',
        'sign-up'          => 'Sign Up',
        'facebook-sign-in' => 'Facebook Sign In',
    ],
    'user'        => [
        'fields' => [
            'nickname'         => 'Nickname',
            'email'            => 'Email',
            'password'         => 'Password',
            'confirm-password' => 'Confirm Password',
            'type-name'        => 'Type',
            'type'             => [
                'general' => 'General',
                'admin'   => 'Admin',
            ],
        ],
    ],
];

------------------
*中文:
resources\lang\zh-TW\validation.php

<?php

return [
  
    /*
    |--------------------------------------------------------------------------
    | Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines contain the default error messages used by
    | the validator class. Some of these rules have multiple versions such
    | as the size rules. Feel free to tweak each of these messages here.
    |
    */
  
    'accepted'             => '必須接受 :attribute。',
    'active_url'           => ':attribute 並非一個有效的網址。',
    'after'                => ':attribute 必須要在 :date 之後。',
    'alpha'                => ':attribute 只能以字母組成。',
    'alpha_dash'           => ':attribute 只能以字母、數字及斜線組成。',
    'alpha_num'            => ':attribute 只能以字母及數字組成。',
    'array'                => ':attribute 必須為陣列。',
    'before'               => ':attribute 必須要在 :date 之前。',
    'between'              => [
        'numeric' => ':attribute 必須介乎 :min 至 :max 之間。',
        'file'    => ':attribute 必須介乎 :min 至 :max kb 之間。 ',
        'string'  => ':attribute 必須介乎 :min 至 :max 個字元之間。',
        'array'   => ':attribute: 必須有 :min - :max 個元素。',
    ],
    'boolean'              => ':attribute 必須為bool值。',
    'confirmed'            => ':attribute 確認欄位的輸入並不相符。',
    'date'                 => ':attribute 並非一個有效的日期。',
    'date_format'          => ':attribute 與 :format 格式不相符。',
    'different'            => ':attribute 與 :other 必須不同。',
    'digits'               => ':attribute 必須是 :digits 位數字。',
    'digits_between'       => ':attribute 必須介乎 :min 至 :max 位數字。',
    'before_or_equal'      => ':attribute 必須小於 :date 。',
    'dimensions'           => 'The :attribute has invalid image dimensions.',
    'distinct'             => ':attribute 已經存在。',
    'email'                => ':attribute 的格式無效。',
    'exists'               => '所選擇的 :attribute 選項無效。',
    'filled'               => ':attribute 不能留空。',
    'image'                => ':attribute 必須是一張圖片。',
    'in'                   => '所選擇的 :attribute 選項無效。',
    'in_array'             => ':attribute 沒有在 :other 中。',
    'integer'              => ':attribute 必須是一個整數。',
    'ip'                   => ':attribute 必須是一個有效的 IP 地址。',
    'json'                 => ':attribute 必須是正確的 JSON 字串。',
    'max'                  => [
        'numeric' => ':attribute 不能大於 :max。',
        'file'    => ':attribute 不能大於 :max kb。',
        'string'  => ':attribute 不能多於 :max 個字元。',
        'array'   => ':attribute 最多有 :max 個元素。',
    ],
    'mimes'                => ':attribute 必須為 :values 的檔案。',
    'min'                  => [
        'numeric' => ':attribute 不能小於 :min。',
        'file'    => ':attribute 不能小於 :min kb。',
        'string'  => ':attribute 不能小於 :min 個字元。',
        'array'   => ':attribute 至少有 :min 個元素。',
    ],
    'not_in'               => '所揀選的 :attribute 選項無效。',
    'numeric'              => ':attribute 必須為一個數字。',
    'present'              => ':attribute 必須存在。',
    'regex'                => ':attribute 的格式錯誤。',
    'required'             => ':attribute 不能留空。',
    'required_if'          => '當 :other 是 :value 時 :attribute 不能留空。',
    'required_unless'      => '當 :other 不是 :value 時 :attribute 不能留空。',
    'required_with'        => '當 :values 出現時 :attribute 不能留空。',
    'required_with_all'    => '當 :values 出現時 :attribute 不能為空。',
    'required_without'     => '當 :values 留空時 :attribute field 不能留空。',
    'required_without_all' => '當 :values 都不出現時 :attribute 不能留空。',
    'same'                 => ':attribute 與 :other 必須相同。',
    'size'                 => [
        'numeric' => ':attribute 的大小必須是 :size。',
        'file'    => ':attribute 的大小必須是 :size kb。',
        'string'  => ':attribute 必須是 :size 個字元。',
        'array'   => ':attribute 必須是 :size 個元素。',
    ],
    'string'               => ':attribute 必須是一個字串。',
    'timezone'             => ':attribute 必須是一個正確的時區值。',
    'unique'               => ':attribute 已經存在。',
    'url'                  => ':attribute 的格式錯誤。',
    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention 'attribute.rule' to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */
    'custom'               => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | Custom Validation Attributes
    |--------------------------------------------------------------------------
    |
    | The following language lines are used to swap attribute place-holders
    | with something more reader friendly such as E-Mail Address instead
    | of 'email'. This simply helps us make messages a little cleaner.
    |
    */
    'attributes'           => [
        // 會員
        'nickname'              => '暱稱',
        'email'                 => '電子信箱',
        'password'              => '密碼',
        'password_confirmation' => '確認密碼',
        // 商品
        'name'            => '商品名稱',
        'name_en'         => '商品英文名稱',
        'introduction'    => '商品介紹',
        'introduction_en' => '商品英文介紹',
        'price'           => '商品價格',
        'remain_count'    => '商品剩餘數量',
    ],
];

-----------------
resources\lang\zh-TW\shop.php

<?php
// 檔案位置:resources/lang/zh-TW/shop.php

return [
    'home'        => '首頁',
    'transaction' => [
        'name'   => '交易',
        'list'   => '交易紀錄',
        'buy'    => '購買',
        'fields' => [
            'buy-count' => '購買數量',
        ],
    ],
    'merchandise' => [
        'name'             => '商品',
        'create'           => '建立商品',
        'manage'           => '管理商品',
        'edit'             => '編輯商品',
        'list'             => '商品列表',
        'page'             => '商品頁',
        'purchase-success' => '購買成功',
        'update'           => '更新商品資訊',
        'fields'           => [
            'id'              => '編號',
            'status-name'     => '商品狀態',
            'status'          => [
                'create' => '建立中',
                'sell'   => '可販售',
            ],
            'name'            => '商品名稱',
            'name-en'         => '商品英文名稱',
            'introduction'    => '商品介紹',
            'introduction-en' => '商品英文介紹',
            'photo'           => '商品照片',
            'price'           => '商品價格',
            'remain-count'    => '商品剩餘數量',
        ],
    ],
    'auth'        => [
        'sign-out'         => '登出',
        'sign-in'          => '登入',
        'sign-up'          => '註冊',
        'facebook-sign-in' => 'Facebook 登入',
    ],
    'user'        => [
        'fields' => [
            'nickname'         => '暱稱',
            'email'            => '電子信箱',
            'password'         => '密碼',
            'confirm-password' => '確認密碼',
            'type-name'        => '帳號類型',
            'type'             => [
                'general' => '一般會員',
                'admin'   => '管理者',
            ],
        ],
    ],
];

========================
*會員註冊:

*建立controller: UserAuthController
*建立function:
 signUpPage
 signUpProcess
 signInpage
 signInProcess
 signOut
*建立view

----------------
*建立controller:
php artisan make:controller UserAuthController

----------------
*設計controller:

app\Http\Controllers\UserAuthController.php

public function signUpProcess(Request $request){

----------------
*接收form資料的方法:

方法1:
$input = request()->all(); //全部資料
$input['password'] //單一資料

方法2:
use Illuminate\Http\Request;
public function signUpProcess(Request $request){}
$input = $request->all(); //全部資料
$request->input('password') //單一資料
$input['password'] //單一資料

----------------
*註冊完成後寄出email通知:

*申請mailgun:
https://www.mailgun.com

SMTP Hostname: smtp.mailgun.org
Port: 587 (recommended)
Username: postmaster@sandbox42524a1092a24a9e9359cca0db28d.mailgun.org
Default Password: d42ce872a1ed3273373a8ee76aa1d24d-acb0b40c-8f8f9

1.安裝套件:
composer require guzzlehttp/guzzle

2.設定.env檔案:
設定.env檔案後,要重新 php artisan serve

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster@sandbox42524a1092a24a9e9359cca0db28d.mailgun.org
MAIL_PASSWORD=d42ce872a1ed3273373a8ee76aa1d24d-acb0b40c-8f8f9
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=eric@eric.com
MAIL_FROM_NAME=eric

5.設計controller:

*方法1:
use Mail;
public function signUpProcess()
{
    //寄送email: 純文字內容
    Mail::raw('測試 Mailgun 寄信服務', function($message){
        $message->from('eric@eric.com', 'eric');
        $message->to('ericarc99@gmail.com');
        $message->subject('測試 Mailgun');
    });
}

參考:
laravel中文:
https://laravel.tw/docs/5.0/mail

*方法2:
use Mail;
public function signUpProcess()
{
    //寄送email: html內容
    // $input = request()->all();
    $mail_binding = [
        // 'nickname' => $input['nickname']
        'nickname' => 'eric'
    ];

    Mail::send('email.signUpEmailNotification', $mail_binding,
    // function($mail) use ($input){
    function($message){
        // $message->to($input['email']);
        $message->from('eric@eric.com', 'eric');
        $message->to('ericarc99@gmail.com');
        $message->subject('註冊成功');
    });
}

view:
resources\views\email\signUpEmailNotification.blade.php

<h1>恭喜 {{ $nickname }} Shop Laravel 註冊成功</h1>

參考:
laravel中文:
https://laravel.tw/docs/5.0/mail

*方法3:
*Mailable:

php artisan make:mail Warning

app\Mail\Warning.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class Warning extends Mailable
{
    use Queueable, SerializesModels;

    public $params;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    //讓外部可以把參數指定進來
    public function __construct($paramsx)
    {
        $this->params = $paramsx;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    { 
        //透過with把參數指定給view
        return $this->subject("警告訊息")
            ->view('email.warning')
            ->with([
                'params' => $this->params,
            ]);
    }
}

*view:
resources\views\email\warning.blade.php

<p>{{ $params['say'] }}</p>

*controller:
php artisan make:controller WarningController

app\Http\Controllers\WarningController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\Warning;
use Mail;

class WarningController extends Controller
{
    public function send(){
        //收件者務必使用 collect 指定二維陣列,每個項目務必包含 "name", "email"
        // $to = collect([
        //     ['name' => 'eric', 'email' => 'ericarc99@gmail.com']
        // ]);
        $to = 'ericarc99@gmail.com';

        //提供給view的參數
        $params = [
            'say' => '測試內容'
        ];

        //內容顯示在瀏覽器(不送出email)
        // echo (new Warning($params))->render(); die;

        //送出email
        Mail::to($to)->send(new Warning($params));
    }
}

*route:
routes\web.php

//寄email
Route::get('/warning','WarningController@send');

參考:
laravel 5.7 發送 E-mail 方法:
php – Laravel – 透過 Gmail 發送 E-mail 信件
https://jsnwork.kiiuo.com/archives/2917/php-laravel-%E9%80%8F%E9%81%8E-gmail-%E7%99%BC%E9%80%81-e-mail-%E4%BF%A1%E4%BB%B6/

laravel:
https://laravel.com/docs/5.7/mail

----------------
*會員註冊controller:
app\Http\Controllers\UserAuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
Use Hash;
use App\Shop\Entity\User;
use Mail;

class UserAuthController extends Controller
{
    /*
    使用者註冊頁面 /user/auth/sign-up GET UserAuthController@signUpPage
    使用者資料新增 /user/auth/sign-up POST UserAuthController@signUpProcess
    使用者登入頁面 /user/auth/sign-in GET UserAuthController@signInpage
    使用者登入處理 /user/auth/sign-in POST UserAuthController@signInProcess
    使用者登出 /user/auth/sign-out GET UserAuthController@signOut
    */

    public function signUpPage(){
        $binding = [
            'title' => trans('shop.auth.sign-up'),
        ];

        return view('auth.signUp', $binding);
    }

    //http://127.0.0.1:8000/user/auth/sign-up
    public function signUpProcess()
    {
        $input = request()->all();

        $rules = [
            'nickname' => [
                'required',
                'max:50',
            ],
            'email' => [
                'required',
                'max:150',
                'email',
            ],
            'password' => [
                'required',
                'same:password_confirmation',
                'min:6',
            ],
            'password_confirmation' => [
                'required',
                'min:6',
            ],
            'type' => [
                'required',
                'in:G,A',
            ],
        ];

        $validator = Validator::make($input, $rules);

        if($validator->fails()){
            return redirect('/user/auth/sign-up')
                ->withErrors($validator)
                ->withInput();
        }

        $input['password'] = Hash::make($input['password']);

        $Users = User::Create($input);

        $mail_binding = [
            'nickname' => $input['nickname'],
            'email' => $input['email'],
        ];

        //寄出email
        // SendSignUpMailJob::dispatch($mail_binding)->onQueue('high');

        //寄送email: 純文字內容
        // Mail::raw('測試 Mailgun 寄信服務', function($message){
        //     $message->from('eric@eric.com', 'eric');
        //     $message->to('ericarc99@gmail.com');
        //     $message->subject('測試 Mailgun');
        // });

        //寄送email: html內容
        $mail_binding = [
            'nickname' => $input['nickname']
            // 'nickname' => 'eric'
        ];

        Mail::send('email.signUpEmailNotification', $mail_binding,
        function($message) use ($input){
        // function($message){
            $message->from('eric@eric.com', 'eric');
            $message->to($input['email']);
            // $message->to('ericarc99@gmail.com');
            $message->subject('註冊成功');
        });

        return redirect('/user/auth/sign-in');
    }

    public function signInPage()
    {
      
    }

    public function signInProcess()
    {
      
    }

    public function signOut()
    {
      
    }
}

========================
*會員登入:



========================
待處理:

x*shop2電子商務網站規劃
x*網址設計規劃
x*建立新專案:shop2
x*建立路由
x*建立資料庫
x*語系設定
x*會員註冊
*會員登入
*會員登出

========================
index:

*shop2電子商務網站規劃
*網址設計規劃
*建立新專案
*建立路由
*建立資料庫
*語系設定
*會員註冊
*會員登入



========================
========================
cd d/php/shop2

php artisan serve

http://127.0.0.1/phpmyadmin/

http://127.0.0.1:8000/

mysql:
cd C:\wamp64\bin\mysql\mysql5.7.14\bin

https://www.w3schools.com/bootstrap4/bootstrap_forms.asp


沒有留言:

張貼留言