Last active
April 6, 2022 08:46
-
-
Save Michael-Stokoe/bf7c16cd8094b49b122849b1c8b9c7a7 to your computer and use it in GitHub Desktop.
Livewire centralised validation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire\Validation; | |
trait HasValidationRules | |
{ | |
public function getValidationClass() | |
{ | |
return new $this->validationClass(); | |
} | |
public function rules($record = null) | |
{ | |
return $this->getValidationClass()->validationRules($record); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire\Users; | |
use Livewire\Component; | |
use App\Http\Livewire\Traits\HasValidationRules; | |
use App\Http\Livewire\ValidationRules\UserRules; | |
class Update extends Component | |
{ | |
use HasValidationRules {rules as traitRules; } | |
public $validationClass = UserRules::class; | |
public $user; | |
public function rules() | |
{ | |
$rules = [ | |
'some_field_not_defined_in_rules_class' => 'required' | |
]; | |
return array_merge($rules, $this->traitRules($this->user)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire\ValidationRules; | |
use Illuminate\Validation\Rule; | |
class UserRules | |
{ | |
public function validationRules($user) | |
{ | |
return [ | |
'user.name' => 'required', | |
'user.status' => Rule::in(['active', 'inactive']), | |
'user.email' => [ | |
'required', | |
'email', | |
Rule::unique('users', 'email')->ignore($user ?? null) | |
], | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment