framework
framework copied to clipboard
[11.x] Added `ModelExists` rule
There is an exists rule to check the existence of a record in the database. You can already pass an Eloquent Model class as the table argument in the Rule::exists() method, but that just extracts the table and connection from the Model. You can apply additional constraints by chaining the where() method, but under the hood, it uses the Illuminate\Database\Query\Builder, not the Illuminate\Database\Eloquent\Builder, so you can't use scopes, for instance.
What we have found in our application is that we are repeating code by writing exists rules and reimplementing the constraints for which we actually already have scopes defined.
This new Rule::modelExists() rule lets you use scopes and other Eloquent Builder features:
Rule::modelExists(User::class)->active()->admin();
By default, it checks the model key (using whereKey()), but you can change that with the optional second argument:
Rule::modelExists(User::class, 'email');
Besides the Model class string, you can also pass a Builder or Model instance:
Rule::modelExists(new User);
Rule::modelExists(User::query()->active());