我验证来自输入的数组:
以下是我的rules
和messages
$rules = [
'fruits' => [
'required',
'array',
'exists:fruits,id',
],
];
$messages = [
'fruits.required' => 'Fruit is required',
'fruits.exists' => 'Given Fruit does not exist',
];
我传递了数据库中存在的水果ID "fruits": [11, 2, 844454],
数组。验证工作。当我提供不存在的水果ID(844454
)时,我会Given Fruit does not exist
。
如何显示给定数组中的哪个ID不存在,以便我可以在消息中显示。
赞Given Fruit 844454 does not exist
?还是Given Fruit(s) 844454, 99999, 333333 do not exist
?
答案 0 :(得分:0)
在 Laravel 5.5 中,您可以像这样创建Custom Validation Rule:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class ExistsID implements Rule
{
protected $notExistIDs;
protected $table;
protected $column;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($table, $column)
{
$this->table = $table;
$this->column = $column;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$IDs = DB::table($this->table)->whereIn($this->column, $value)->pluck($this->column)->toArray();
$this->notExistIDs = array_diff($value, $IDs);
return count($this->notExistIDs) == 0;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return strtr("Given :table :ids does not exist", [
':table' => $this->table,
':ids' => json_encode($this->notExistIDs)
]);
}
}
规则:
$rules = [
'fruits' => [
'required',
'array',
new ExistsID('fruits', 'id')
],
];
结果:
Given fruits {\"4\":\"9999\"} does not exist
代码为different in Laravel 5.3,但您可以尝试相同的想法。快乐的编码。