Laravel 有個很好用的 FormRequest , 可以把表單驗證的代碼從控制器層剝離,增加代碼的可讀性。
除了自帶的表單驗證規則外,很多時候我們需要自定義閉包規則,這有可能會用到其他字段的輸入值。
具體代碼如下:
<?php namespace App\Http\Requests; use App\Models\LaunchChannelContactWay; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Request; class LaunchRequest 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() { $path = Request::getPathInfo(); switch ($path){ case '/api/add_launch_channel_contact_way': $rules=[ 'channel_id'=>[ 'required', 'int', 'exists:launch_channels,id', function($attribute, $value, $fail){//自定義驗證閉包 $unique=LaunchChannelContactWay::query() ->where('launch_channel_id',$value) ->where('activity_name',$this->input('activity_name'))//獲取activity_name字段值 ->count(); if($unique>0){ $fail('渠道活動配置已存在'); } }], ]; break; default: $rules = []; break; } return $rules; } }
Enjoy it !
