你可以使用Hash facade的check方法,来自docs:
use Illuminate\Support\Facades\Hash;
// some code
if (Hash::check('plain-text', $hashedElement)) {
// The elements match...
}
现在,您可以在 Custom Validation Rule 中使用它:
1。创建规则类
php artisan make:rule HashedNameCheck
2。自定义类
app\Rules\HashedNameCheck.php
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash; // <-- notice.
class HashedNameCheck implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// here you get the hashed name stored in your database (?)
$hashedName = App\User::find(1)->name;
// next, you compare this with the received value.
return Hash::check($value, $hashedName);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute does not match with the stored value.';
}
}
3。应用规则。
在你的控制器中使用它:
$request->validate([
// some other validation rules..
'name' => ['required', 'unique:users', new HashedNameCheck],
]);
或在您的自定义 Form Request 类中:
public function rules()
{
return [
// some other validation rules..
'name' => ['required','unique:users', new HashedNameCheck],
];
}