PHPackages                             timacdonald/rule-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. timacdonald/rule-builder

ActiveUtility[Validation &amp; Sanitization](/categories/validation)

timacdonald/rule-builder
========================

A fluent rule builder for Laravel validation rule generation.

v4.0.0(7y ago)1027.7k↓50%3[1 PRs](https://github.com/timacdonald/rule-builder/pulls)MITPHPPHP &gt;=7.0

Since Jan 3Pushed 5y ago2 watchersCompare

[ Source](https://github.com/timacdonald/rule-builder)[ Packagist](https://packagist.org/packages/timacdonald/rule-builder)[ RSS](/packages/timacdonald-rule-builder/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (28)Used By (0)

Fluent Validation Rule Builder for Laravel
==========================================

[](#fluent-validation-rule-builder-for-laravel)

[![Latest Stable Version](https://camo.githubusercontent.com/4ac149e250b1c1e8e980dc8286710c6ae06692608900f20e09094c7d13b09389/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f72756c652d6275696c6465722f762f737461626c65)](https://packagist.org/packages/timacdonald/rule-builder) [![Total Downloads](https://camo.githubusercontent.com/5fb718f97ef8172a8315abad04799d35421ec225548db5237c07652a0bffb42c/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f72756c652d6275696c6465722f646f776e6c6f616473)](https://packagist.org/packages/timacdonald/rule-builder) [![License](https://camo.githubusercontent.com/5c5c78138cd81a62976523f95af84fe40ac02166d6d98f0760de4856f8e2f4f4/68747470733a2f2f706f7365722e707567782e6f72672f74696d6163646f6e616c642f72756c652d6275696c6465722f6c6963656e7365)](https://packagist.org/packages/timacdonald/rule-builder)

A fluent interface to generate Laravel validation rules with helpers. It proxies to the built in Laravel validation rules where possible and also adds some sugar such as `min` and `max` helpers, ability to pass `Carbon` instances to date rules, as well as a handy `when` method (inline that `sometimes` rule!). I've also add a `foreignKey` and `unique` rule that allows you to pass in classes or instances. I love it - get around it yo!

Installation
------------

[](#installation)

You can install using [composer](https://getcomposer.org/) from [Packagist](https://packagist.org/packages/timacdonald/rule-builder)

```
$ composer require timacdonald/rule-builder

```

Usage
-----

[](#usage)

All the examples assume you have included the `use TiMacDonald\Validation\Rule;` statement already.

```
$rules = [
    'name' => Rule::required()
                  ->string(3, 255)
                  ->get(),

    'email' => Rule::required()
                   ->string()
                   ->email(255)
                   ->unique('users')
                   ->get(),

    'password' => Rule::required()
                      ->string(6)
                      ->confirmed()
                      ->get(),
];
```

Don't forget you need to call the final `get()` method. Using this instead of the standard Laravel 'stringy' way is a little verbose, but I actually really enjoy using it this way - you might not ¯\\\_(ツ)\_/¯

### Min / Max Helpers

[](#min--max-helpers)

These methods allow for optional `$min` and / or `$max` parameters to help validate size restrictions on the data. Here is a list of the available helpers and their parameters:

```
Rule::activeUrl($max)
    ->alpha($min, $max)
    ->alphaDash($min, $max)
    ->alphaNum($min, $max)
    ->array($min, $max)
    ->email($max)
    ->file($max)
    ->image($max)
    ->integer($min, $max)
    ->json($max)
    ->numeric($min, $max)
    ->string($min, $max)
    ->url($max)
```

Example usage of these helper methods:

```
$rules = [
    'age' => Rule::integer(21)->get(),
    'dollars' => Rule::numeric(0, 999.99)->get(),
    'email' => Rule::email(255)->get(),
];
```

If you pass `null` as a `min` or `max` helper, the value will be skipped. This is mostly handy when there is both a `min` and `max` helper, but you do not want to add a `min` e.g. `Rule::string(null, 255)->get()`.

### Custom Validation Rules

[](#custom-validation-rules)

Laravel has introduced some very handy [custom validation classes](https://laravel.com/docs/5.5/validation#custom-validation-rules). We've made it simple to add these rules as well. Chances are you would probably just implement all the required rules in a single validation class and not require the rule builder, but in case you do you can do the following:

```
$rules = [
    'notifications' => Rule::add(new MyValidationRule)
                           ->add(new MyOtherValidationRule)
                           ->get(),
];
```

### Carbon with Date Rules

[](#carbon-with-date-rules)

You can now pass a `Carbon` instance to the date rules: `after`, `after_or_equal`, `before`, `before_or_equal`.

```
$rules = [
    'due_date' => Rule::after(Carbon::now()->addYear())->get()
];
```

Laravel's date rules utilise PHP's [`strtotime`](http://php.net/manual/en/function.strtotime.php) function to parse the provided date. As recommended by the PHP docs, the `Carbon` instance is formatted as ISO 8601 to avoid any date ambiguity.

### Conditional Rules

[](#conditional-rules)

You can add rules conditionally using the `when()` method. This is similar to Laravel's `sometimes` method, however it is inline with your rules.

```
$rules = [
    'username' => Rule::required()->when($userNameIsEmail, function ($rule) {
        $rule->email();
    })->get(),
];
```

### Proxy to Laravel Rule Classes

[](#proxy-to-laravel-rule-classes)

Laravel comes with some built in rule classes. If one is present, we simply proxy to it and keep on rocking, it's seamless. The `unique` rule is a built in Laravel class with a `where` method - check this out:

```
$rules = [
    'email' => Rule::unique('users')->where(function ($query) {
                   $query->where('account_id', 1);
               })->email(255)->get(),
];
```

Just make sure you call any methods that apply to the proxied rule directly after the initial call to the proxy method.

### Foreign Key Validation

[](#foreign-key-validation)

Want to stop using the `exists` rule and be able to rock those foreign key validation rules like a boss? We'll look no further:

```
$rules = [
  'subscription_id' => Rule::foreignKey(Subscription::class)->get(),
];
```

You can even pass in an instance if you want! The class or instance will be queried to determine the table names etc for you #magic

### Unique Rule with Class or Instance.

[](#unique-rule-with-class-or-instance)

As [suggested on internals](https://github.com/laravel/internals/issues/591#issuecomment-302018299) you are now able to apply the unique constraint using a models class name, or an instance, instead of passing in the table name as a plain string (similar to the `foreignKey` rule). This method still proxies to Laravel's built in unique rule, so you can continue to chain rules.

```
$rules = [
  'title' => Rule::unique(Post::class, 'title')->get(),
];
```

### URL with specific hostname extension

[](#url-with-specific-hostname-extension)

If you need to validate that the URL has an extension (TLD or whatnot) or even a specific extension (.org.au) this validation rule is for you!

```
$rules = [
    'website' => Rule::urlWithHostExtension(['.org.au'])->get(), // only .org.au extensions allowed
    'domain' => Rule::urlWithHostExtension()->get(), //and extension
];
```

This rule first applied the `url` rule and then adds a regex pattern to check for the extensions existence.

### URL with specific scheme

[](#url-with-specific-scheme)

It can be handy to check that a scheme is perhaps `https` or `fb` or some other URL scheme. This is a handy rule to ensure this is enforced.

```
$rules = [
    'profile' => Rule::urlWithScheme(['https', 'fb'])->get(),
];
```

### Max Digits Helper Rule

[](#max-digits-helper-rule)

I've added a `maxDigits` rule after reading [this suggestion](https://github.com/laravel/internals/issues/673) over on internals. This is just an alias to the `digits_between` rule.

```
$rules = [
  'amount' => Rule::digitsMax(10)->get(),
];

```

Which is equivalent to `digits_between:0,10`.

### Extending with Custom Rules

[](#extending-with-custom-rules)

If you are [creating your own validation rules](https://laravel.com/docs/5.4/validation#custom-validation-rules) and wish to use them with the rule builder you can simply extend the rule builder. You will want to do this in a [service provider](https://laravel.com/docs/5.4/providers).

```
