DEV Community

Abrar Ahmad
Abrar Ahmad

Posted on

Question: How to better structure Laravel Livewire code and components?

I'm building an app using Livewire. If you have some experience with Livewire please take some time to answer.

I'm trying to keep my livewire components code clean. How we can separate validation logic just like custom Requests in the controller as there is not Request object in the Livewire component.

My current approach: I make separate method for validation for now? But I'm looking for something much better like custom Requests.

class Add extends Component
{
 public function store()
    {
     $this->Validation();

     $property = new Property();
     $property->user_id = ...

    }
}

Enter fullscreen mode Exit fullscreen mode

Also, If is there any better approach for structuring components? My current approach is below:

Alt Text

Any suggestions will be appreciated.

Top comments (2)

Collapse
 
messerli90 profile image
Michael Messerli

A little late to respond but one accepted way to extract validation logic is to add it to the model. It looks like this:

// Model.php
public static function validationRules()
    {
        return [
            'name' => ['required', 'string', 'max:250'],
            'other_attr' => ['nullable', 'url', 'max:250'],
            'another_attr' => ['nullable', 'string', 'max:250']
        ];
    }

Then in Livewire you can do:

// Livewire component
public function store() {
    $this->validate(Model::validationRules);
}
Collapse
 
abrardev99 profile image
Abrar Ahmad

That's pretty nice. But it will be more pretty strecture like CustomFormRequest. Anyway Thank You so much