Skip to content
This repository has been archived by the owner on Sep 3, 2021. It is now read-only.

Commit

Permalink
建立Request來做資料整理及檢查
Browse files Browse the repository at this point in the history
  • Loading branch information
tad0616 committed Jun 1, 2019
1 parent 6efe5a5 commit e4c2941
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 5 deletions.
4 changes: 3 additions & 1 deletion app/Http/Controllers/CartController.php
Expand Up @@ -4,6 +4,7 @@

use App\Cart;
use Illuminate\Http\Request;
use App\Http\Requests\CartRequest;

class CartController extends Controller
{
Expand Down Expand Up @@ -33,8 +34,9 @@ public function create()
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
public function store(CartRequest $request)
{

Cart::create([
'user_id' => $request->user()->id,
'product_id' => $request->product_id,
Expand Down
58 changes: 58 additions & 0 deletions app/Http/Requests/CartRequest.php
@@ -0,0 +1,58 @@
<?php

namespace App\Http\Requests;

use App\Product;
use Illuminate\Foundation\Http\FormRequest;

class CartRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'product_id' => [
'required',
function ($attribute, $value, $fail) {
if (!$product = Product::find($value)) {
return $fail('該商品不存在');
}
if (!$product->on_sale) {
return $fail('該商品未上架');
}
},
],
'amount' => ['required', 'integer', 'min:1'],
];
}

public function attributes()
{
return [
'amount' => '商品數量',
];
}

public function messages()
{
return [
'required' => '請選擇商品',
'min' => '「:attribute」至少要 :min 個',
];
}

}
19 changes: 15 additions & 4 deletions resources/views/product/add2cart.blade.php
Expand Up @@ -7,12 +7,23 @@
.then(function () { // 請求成功時執行:
swal('加入購物車成功', '', 'success');
}, function (error) { // 請求失敗時執行:

console.log('error.response.status = ' + error.response.status);
if (error.response.status === 422) {
var html = '<div>';
_.each(error.response.data.errors, function (errors) {
_.each(errors, function (error) {
html += error + '<br>';
})
});
html += '</div>';
swal({content: $(html)[0], icon: 'error'})
} else if(error.response.status === 500) {
swal('系統錯誤', '', 'error');
}

@guest
swal('請先登入', '', 'error');
@endguest

@auth
swal('系統錯誤', '', 'error');
@endauth
})
});

0 comments on commit e4c2941

Please sign in to comment.