iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
Modern Web

Laravel 是甚麼系列 第 15

加入條件判斷

  • 分享至 

  • xImage
  •  

後端程式碼加入條件判斷:
加入套件: use Illuminate\Support\Facades\Validator;

https://ithelp.ithome.com.tw/upload/images/20250818/20119035GbSqQyskO4.png

從store程式碼修改
原來:

https://ithelp.ithome.com.tw/upload/images/20250818/20119035Q7zvuFFVwG.png

public function store(Request $request)
   {
       $form = $request->all();
       DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
'product_id' => $form['product_id'],
'quantity' => $form['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
   }
   

修改後:欄位必填
https://ithelp.ithome.com.tw/upload/images/20250818/20119035GKH4hqP1Uh.png

public function store(Request $request)
   {
       //$form = $request->all();
$validator = Validator::make($request->all(),[
   'cart_id'=>'required',
   'product_id'=>'required',
   'quantity'=>'required'
]);
if($validator->fails()){
   return response($validator->errors(),400);
}

       DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
'product_id' => $form['product_id'],
'quantity' => $form['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
   }

API的命名 - 比 _ 正確
Route::resource('cart-items', 'CartItemController');

https://ithelp.ithome.com.tw/upload/images/20250818/20119035sEmAgG9tQ7.png

記得terminal要重新啟動php artisan serve
https://ithelp.ithome.com.tw/upload/images/20250818/20119035c56YiQQ33m.png

POSTMAN測試一個不填會報錯
https://ithelp.ithome.com.tw/upload/images/20250818/20119035zvLTF4C2bo.png

POSTMAN測試3個不填會報錯
https://ithelp.ithome.com.tw/upload/images/20250818/20119035cDL5Ezb2Gs.png


指定填入只能數字

https://ithelp.ithome.com.tw/upload/images/20250818/20119035fZlj70vM0X.png

程式碼:

public function store(Request $request)
    {
        //$form = $request->all();
$validator = Validator::make($request->all(),[
    'cart_id'=>'required|integer',
    'product_id'=>'required|integer',
    'quantity'=>'required|integer'
]);
if($validator->fails()){
    return response($validator->errors(),400);
}

        DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
'product_id' => $form['product_id'],
'quantity' => $form['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
    }
    
    ````

--------
POSTMAN測試
 ![https://ithelp.ithome.com.tw/upload/images/20250818/20119035FPDirLDUde.png](https://ithelp.ithome.com.tw/upload/images/20250818/20119035FPDirLDUde.png)
 
-------
指定填入範圍'quantity'=>'required|integer|between:1,10'

![https://ithelp.ithome.com.tw/upload/images/20250818/20119035HXhiZnc7Gg.png](https://ithelp.ithome.com.tw/upload/images/20250818/20119035HXhiZnc7Gg.png)
 
程式碼

public function store(Request $request)
{
//$form = $request->all();
$validator = Validator::make($request->all(),[
'cart_id'=>'required|integer',
'product_id'=>'required|integer',
'quantity'=>'required|integer|between:1,10'
]);
if($validator->fails()){
return response($validator->errors(),400);
}

    DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],

'product_id' => $form['product_id'],
'quantity' => $form['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
}

````

POSTMAN測試
https://ithelp.ithome.com.tw/upload/images/20250818/20119035tOrB3hOPmU.png


報錯訊息變中文

https://ithelp.ithome.com.tw/upload/images/20250818/2011903532MziXQzqw.png

程式碼

public function store(Request $request)
    {
$messages =[
'required' => ':attribute 是必要的'
];

        //$form = $request->all();
$validator = Validator::make($request->all(),[
    'cart_id'=>'required|integer',
    'product_id'=>'required|integer',
    'quantity'=>'required|integer|between:1,10'
],$messages);
if($validator->fails()){
    return response($validator->errors(),400);
}

        DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
'product_id' => $form['product_id'],
'quantity' => $form['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
    }
    
    ````

POSTMAN測試 

![https://ithelp.ithome.com.tw/upload/images/20250818/20119035GkECDAJl3U.png](https://ithelp.ithome.com.tw/upload/images/20250818/20119035GkECDAJl3U.png)
不在範圍內顯示變中文
 ![https://ithelp.ithome.com.tw/upload/images/20250818/20119035ZBz58fMwaf.png](https://ithelp.ithome.com.tw/upload/images/20250818/20119035ZBz58fMwaf.png)
---------------
全部驗證成功顯示true
 ![https://ithelp.ithome.com.tw/upload/images/20250818/20119035yOWhVSCRvs.png](https://ithelp.ithome.com.tw/upload/images/20250818/20119035yOWhVSCRvs.png)
 
 
程式碼


public function store(Request $request)
{
$messages =[
'required' => ':attribute 是必要的'
];

    //$form = $request->all();

$validator = Validator::make($request->all(),[
'cart_id'=>'required|integer',
'product_id'=>'required|integer',
'quantity'=>'required|integer|between:1,10'
],$messages);
if($validator->fails()){
return response($validator->errors(),400);
}
$validateData = $validator->validate();

    //DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
    DB::table('cart_items')->insert(['cart_id' => $validateData['cart_id'],

//'product_id' => $form['product_id'],
'product_id' => $validateData['product_id'],
//'quantity' => $form['quantity'],
'quantity' => $validateData['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
}

````

POSTMAN測試
https://ithelp.ithome.com.tw/upload/images/20250818/20119035cF4uZvxzqE.png

新增檔案來做數量驗證:
帶入 繼承概念
在terminal
用指令加入資料夾裡面含有php artisan make:request UpdateCartItem

https://ithelp.ithome.com.tw/upload/images/20250818/20119035aVLhFv1hSL.png
產生的UpdateCartItem

裡面的程式碼:
https://ithelp.ithome.com.tw/upload/images/20250818/20119035KnQXZcens7.png

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

把return false;改成return true;

https://ithelp.ithome.com.tw/upload/images/20250818/20119035lUUecFG8O0.png

修改public function rules()內容

https://ithelp.ithome.com.tw/upload/images/20250818/201190353gZU4nvjcG.png

程式碼

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'quantity'=>'required|integer|between:1,10'
        ];
    }
    public function messages()
    {
        return [
            'quantity.between'=>'數量必須小於10'
        ];
    }

}

再新增一個檔案
https://ithelp.ithome.com.tw/upload/images/20250818/20119035kVibneshWJ.png
填入內容
https://ithelp.ithome.com.tw/upload/images/20250818/201190358slPTQSb0W.png
加入套件,改裡面的程式碼

https://ithelp.ithome.com.tw/upload/images/20250818/20119035lgsGm57mgO.png

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class APIRequest extends FormRequest
{
   protected function failedValidation(Validator $validator)
{
   throw new HttpResponseException(response(['errors'=>$validator->errors()],400));
}
}

再修改UpdateCartItem裡面去繼承他
程式碼:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'quantity'=>'required|integer|between:1,10'
        ];
    }
    public function messages()
    {
        return [
            'quantity.between'=>'數量必須小於10'
        ];
    }

}

https://ithelp.ithome.com.tw/upload/images/20250818/2011903531GIRRBp7T.png
改CartItemController 裡面的update程式碼

public function update(UpdateCartItem $request, $id)
   {
       //$form = $request->all();
       $form = $request->validate();
       DB::table('cart_items')->where('id',$id)
       ->update([
'quantity' => $form['quantity'],
'updated_at' => now()]);

//return response(true);
return response()->json(true);
   }

引用套件UpdateCartItem

加入use App\Http\Requests\UpdateCartItem;

https://ithelp.ithome.com.tw/upload/images/20250818/20119035wMPeVZ6Jq0.png

啟動serve的指令: php artisan serve
https://ithelp.ithome.com.tw/upload/images/20250818/20119035pZbZnHwh1d.png
可以更新的程式碼
https://ithelp.ithome.com.tw/upload/images/20250818/20119035kjEwneiFR3.png

public function update(UpdateCartItem $request, $id)
   {
       $form = $request->validated(); 
       DB::table('cart_items')->where('id',$id)
       ->update([
'quantity' => $form['quantity'],
'updated_at' => now()]);

return response()->json(true);
   }
   

用POSTMAN測試有顯示中文報錯
https://ithelp.ithome.com.tw/upload/images/20250818/20119035iEIHlJL6hn.png
符合範圍時顯示true
https://ithelp.ithome.com.tw/upload/images/20250818/20119035GuKUCUnbbq.png
大家明天見~ 有些圖跟程式碼 ~無法顯示得很美~大家應該可以區分吧~?
https://ithelp.ithome.com.tw/upload/images/20250818/201190357ReqW2ZDr7.png


上一篇
增加購物車裡面數量
下一篇
關於ORM
系列文
Laravel 是甚麼30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言