我想忽略 FormRequest 類中的一個輸入。以前,我已經在我之前的 Laravel 專案中使用完全相同的代碼完成了它(之前的 Laravel 專案是 Laravel 版本 7)。這是我忽略驗證的代碼:
class UserRequest extends FormRequest
{
protected $user;
public function __construct(Request $request)
{
$this->user = $request->route()->client;
}
public function rules()
{
return [
'email' => ['nullable', 'string', 'email', 'max:100', 'unique:users,email,'.$this->user.',user_id'],
];
}
“$request->route()->client”這行代碼是獲取提交的表單請求資料(client是web.php檔案里面的路由之一)。但是當我在當前專案中嘗試這段代碼時(當前專案是 Laravel 8)。結果是電子郵件沒有被忽略。
我猜 Laravel 8 中有一些關于 FormRequest 的新東西?我該如何解決這個問題?
更新
這是我的路線(web.php)代碼:
Route::middleware('auth')->group(function () {
Route::resource('users', UserController::class);
這是我的用戶表結構:

我使用了資源控制器,所以路線很簡單。
uj5u.com熱心網友回復:
嘗試以下方式
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UserRequest 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<string, mixed>
*/
public function rules()
{
return [
'email' => [
'nullable', 'string', 'email', 'max:100',
Rule::unique('users','email')->ignore($this->route()->client,'user_id'),
],
];
}
}
并忽略方法接受兩個引數
ignore($id, $idColumn = null)
對于第二列默認值,它將id列視為主鍵。如果不是,那么我們應該指定列名。
所以不需要使用建構式和所有
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/512457.html
標籤:php拉拉维尔验证
上一篇:如何更改UserCreationForm屬性,例如error_messges、標簽等?
下一篇:在索引頁面上獲取帖子
