Skip to content

Instantly share code, notes, and snippets.

@LegitDongo
Last active May 24, 2023 19:17
Show Gist options
  • Save LegitDongo/3138fa58789ba8ba97d1eaf1b16d18d6 to your computer and use it in GitHub Desktop.
Save LegitDongo/3138fa58789ba8ba97d1eaf1b16d18d6 to your computer and use it in GitHub Desktop.
RequiredIfIn - Laravel validation rule requiring a field when a value exists in another field that is an array.
<?php
namespace App\Rules;
use App\Traits\Instantiate;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use InvalidArgumentException;
class RequiredIfIn implements Rule, DataAwareRule, ValidatorAwareRule
{
use Instantiate;
protected $data = [];
protected string|bool $lookIn = false;
protected string|bool $lookFor = false;
protected \Illuminate\Validation\Validator $validator;
public function passes($attribute, $value)
{
if ($this->lookIn === false || $this->lookFor === false) {
throw new InvalidArgumentException('RequiredIfIn requires a place to look and a value to look for');
}
if (($this->data[$this->lookIn] ?? false) && in_array($this->lookFor, $this->data[$this->lookIn], true)) {
return is_string($value);
}
return true;
}
public function message()
{
return 'The :attribute'
. ' field is required when the "' . $this->lookFor
. '" option in ' . ($this->validator->customAttributes[$this->lookIn] ?? $this->lookIn) . ' is checked.';
}
public function setData($data)
{
$this->data = $data;
return $this;
}
public function setValidator($validator)
{
$this->validator = $validator;
return $this;
}
public function LookIn(string $lookInArray): self
{
$this->lookIn = $lookInArray;
return $this;
}
public function LookFor(string $lookupValue): self
{
$this->lookFor = $lookupValue;
return $this;
}
}
<?php
namespace App\Traits;
trait Instantiate
{
public static function make(...$arguments): self
{
return new static(...$arguments);
}
}
<?php
namespace App\Http\Requests;
use App\Rules\RequiredIfIn;
use Illuminate\Foundation\Http\FormRequest;
class UseItRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'test' => 'required',
'test-detail' => RequiredIfIn::make()
->LookIn('test')
->LookFor('one of the values')
];
}
public function attributes()
{
return [
'test' => 'Even Uses Set Attributes',
'test-detail' => 'Detail'
];
}
}
// Error output:
// The Detail field is required when the "one of the values" option in Even Uses Set Attributes is checked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment