Laravel 5.5 validation ruleception (rule inside rule)

Laravel’s validation Rule

use Illuminate\Support\Facades\Validator;
use
Illuminate\Contracts\Validation\Rule;

class PhoneUnique implements Rule
{
protected $user;

public function __construct(User $user)
{
$this->user = $user;
}

public function passes($attribute, $value)
{
// If it hasn't changed, then it passes
if (!$value || $this->player->phone === $value) {
return true;
}
$validator = Validator::make([
'phone' => $value
], [
'phone' => 'unique:users'
]);

return $validator->passes();

}

public function message()
{
return 'Player\'s phone must be unique.';
}
}
$user = auth()->user();request()->validate([
'phone' => ['required', new PhoneUnique($user)]
]);

Make it prettier

use Illuminate\Contracts\Validation\Rule;

class PlayerPhoneUnique extends BaseRule implements Rule
{
protected $user;

public function __construct(User $user)
{
$this->user = $user;
}

public function passes($attribute, $value)
{
if (!$value || $this->player->phone === $value) {
return true;
}

// Needs the attribute parameter cause that's the field used by unique
return $this->validate($value, 'unique:players', $attribute);
}

public function message()
{
return 'Player\'s phone must be unique.';
}
}

More examples

  • Multiple rules on same validator
public function passes($attribute, $value)
{
return $this->validate($value, [
'required', 'digits:10', new PhoneUnique($this->user)
], $attribute);
}
  • Multiple validators
public function passes($attr, $value)
{
if (! $this->validate($value, ['required', 'digits:10'], $attr)
) {
return false;
}
return $this->validate($value,
new PhoneUnique($this->user), $attr);
}
public function message()
{
$errors = $this->getValidator()->errors();

if ($errors->any()) {
return $errors->all();
}

return 'Some other error';
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

They could arguably be applied to treating Covid-19 as well

[What Is] SDN & NFV | PANTHEON.tech

JMeter Plugins -A Comprehensive Guide To The Plugins Manager

Fastlane scan- automate testing

Setting-up Airflow on Windows 10 without Docker

A/B testing (My CXL experience)

Portainer to manage Docker containers in AWS ECS Cluster Instances - sithum devops

Scrollette.py Documentation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Juampi Barreto

Juampi Barreto

More from Medium

How is Laravel work?

How Laravel work

What’s New In Laravel 9 (Part 1)

Maintain statistics about your database tables using Laravel and triggers