Last active
July 29, 2023 00:03
-
-
Save x7ryan/6a99684e2459298459e29b7ae6a3fc9f to your computer and use it in GitHub Desktop.
A simple Laravel Livewire trait to include rules and messages from a Laravel FormRequest Class. Simply use this trait and define a protected property useFormRequest as a reference to the FormRequest class you wish to use. This can be used to share validation logic between livewire components and traditonal Laravel controllers, for example when u…
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; | |
use Livewire\Component; | |
use App\Http\Livewire\Concerns\FormRequest; | |
class ExampleUsage extends Component | |
{ | |
use FormRequest; | |
protected $useFormRequest = \App\Http\Requests\TestRequest::class; | |
} |
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\Concerns; | |
use Livewire\Exceptions\PropertyNotFoundException; | |
trait FormRequest | |
{ | |
protected function rules() | |
{ | |
if (!isset($this->useFormRequest)) { | |
throw new PropertyNotFoundException('useFormRequest', get_class()); | |
} | |
return (new $this->useFormRequest)->rules(); | |
} | |
protected function messages() | |
{ | |
if (!isset($this->useFormRequest)) { | |
throw new PropertyNotFoundException('useFormRequest', get_class()); | |
} | |
return (new $this->useFormRequest)->messages(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment