You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule; use Illuminate\Database\Eloquent\Model as Model; use Jenssegers\Mongodb\Eloquent\Model as Document;
class ExistsRule implements Rule { CONST FIELD = '_id';
private Model|Document $model;
private array $invalidItems;
/** * Create a new rule instance. * * @param Model|Document $model * @param string $field */ public function __construct(Model|Document $model) { $this->model = $model; }
/** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { $valid = true; $value = collect($value); // if value is empty do not validate
if ($value->isEmpty()) { return $valid; } // query to fetch records base on field and value.
$validCollection = $this->model->select(self::FIELD) ->whereIn(self::FIELD, $value->toArray()) ->withoutTrash() ->get()->map(fn($m) => $m->{self::FIELD});
// check if all values are existed.
$valid = $value->count() === $validCollection->count(); // extract invalid values.
$this->invalidItems = $value->diff($validCollection)->toArray();
return $valid; }
/** * Get the validation error message. * * @return string */ public function message() { return implode(',', $this->invalidItems) . (count($this->invalidItems) > 1 ? ' are ' : ' is ') . 'invalid!'; } }
|