DEV Community

Cover image for Validate a local Variable in Laravel Livewire.
Jitesh Dhamaniya
Jitesh Dhamaniya

Posted on • Updated on

Validate a local Variable in Laravel Livewire.

Laravel LiveWire is a phenomenal framework for Laravel. Using it for 1 hour makes you fall in love with it. I use nowadays for any project i am doing in Laravel. Anyways recently i had to validate a variable which was not a public one.

for Public variables its straightforward you define

protected $rules = []
Enter fullscreen mode Exit fullscreen mode

or define

protected function rules(){
    return []
} 
Enter fullscreen mode Exit fullscreen mode

and then call $this->validate(). Simple.

But my requirement was to validate a variable which i was getting on click call (wire.click).

<a wire:click="changeStatus({{ $row->id }},4)">Mark as Approve</a>
Enter fullscreen mode Exit fullscreen mode

little did i know Livewire does have solution for it as well for validating a local variable you do something like this

 $validate = Validator::make(
            ['status' => $status], // here you assign value for validation
            ['status' => 'required|integer|min:1|max:2'],
            ['required' => 'The :attribute field is required'],
        )->validate();
Enter fullscreen mode Exit fullscreen mode

This is my complete code if you interested.

public function changeStatus($id, $status){
        $request = PayoutRequest::find($id);

        $validate = Validator::make(
            ['status' => $status],
            ['status' => 'required|integer|min:1|max:2'],
            ['required' => 'The :attribute field is required'],
        )->validate();

        $request->status = $status;
        $request->save();
        session()->flash('status', "Status has been updated.");
    }
Enter fullscreen mode Exit fullscreen mode

hope this will help someone save some time.

Top comments (3)

Collapse
 
mahdipishguy profile image
Mahdi Pishguy • Edited

You don't need to validate all values by validator for every fields, however this is a simple but i think you can do that for each variable as you want to validate by this code:

public function updated($field)
{
    try {
        $this->validateOnly($field);
    } catch (ValidationException $e) {
        $validator = $e->validator;
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jiteshdhamaniya profile image
Jitesh Dhamaniya

this is when property is public yes. however i wrote post incase you want to validate a local variable which does not have existence on component.

Collapse
 
mahdipishguy profile image
Mahdi Pishguy

oh, i get it now, you are right