Skip to content

Instantly share code, notes, and snippets.

@x7ryan
Last active July 29, 2023 00:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save x7ryan/6a99684e2459298459e29b7ae6a3fc9f to your computer and use it in GitHub Desktop.
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…
<?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;
}
<?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