Skip to content

Upgrade to v2

This guide covers the breaking changes between v1 and v2.

Three things to change

1. Remove data from the constructor

In v1 you could pass the initial data to the constructor:

// v1
$gate = new Gate(['foo' => 'bar']);

In v2 the constructor takes no arguments. Pass data to validate() instead (see below).

2. Remove setData() calls

setData() no longer exists. Pass the data directly to validate().

3. Capture the result of validate()

validate() now accepts the input data and returns a ValidationResult instead of a bool. The result object has get() and getErrors() that mirror the old $gate->get() / $gate->getErrors(), so the only change inside your if-block is the variable name:

// v1
$gate->setData($_POST);
if ($gate->validate()) {
    $username = $gate->get('username');
    $all      = $gate->getData();
} else {
    $errors = $gate->getErrors();
}

// v2 — rename $gate to $result inside the block, that's it
$result = $gate->validate($_POST);
if ($result->valid) {
    $username = $result->get('username');
    $all      = $result->getData();
} else {
    $errors = $result->getErrors();
}

If your v1 code already passed data directly to validate(), the change is even smaller:

// v1
if ($gate->validate($_POST)) { ... }

// v2
$result = $gate->validate($_POST);
if ($result->valid) { ... }

What stays the same

  • accepts(), accept(), addField(), addFields() — unchanged
  • All field definition syntax (strings, objects, callables, 'required')
  • Gate::assert()
  • All filters and validators

Full before/after example

// v1
$gate = new Gate();
$gate->accepts([
    'username' => ['required', 'trim', 'strLen:3:20'],
    'password' => ['required', 'strLen:8', 'equals:password_confirmation'],
    'email'    => ['required', 'trim', 'emailAddress'],
]);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $gate->validate($_POST)) {
    $user->username = $gate->get('username');
    $user->email    = $gate->get('email');
    $user->save();
} else {
    $errors = $gate->getErrors();
}
// v2
$gate = new Gate();
$gate->accepts([
    'username' => ['required', 'trim', 'strLen:3:20'],
    'password' => ['required', 'strLen:8', 'equals:password_confirmation'],
    'email'    => ['required', 'trim', 'emailAddress'],
]);

$result = $gate->validate($_POST);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $result->valid) {
    $user->username = $result->get('username');
    $user->email    = $result->get('email');
    $user->save();
} else {
    $errors = $result->getErrors();
}