Fazle Rabbi

Form Validation in Livewire

form validation in Livewire

Form validation without not refreshing the page is really a handy thing. We can do this with Livewire also. In this article we will know how to do form validation in Livewire. Though Livewire language is almost similar to Laravel, we have to be careful dealing with the form variable at some extends. We have to remember that livewire comes as a replacement of clumsy, head turning JavaScript with the same functional capability but in the language of our beloved Laravel. Now Like JavaScript, Livewire can also do all that dynamic stuff maintaining same concept as JavaScript

Livewire Class-view component pair:

In normal Laravel’s architecture we see that there remains a controller file, a blade file for view and a model file. Like this in Livewire, there is a controller like class file which is directly bonded with a view component file. All the logic and property changes are transacted between these two without any page reloading, just like JavaScript Ajax request. Like Laravel we would have some validation logics and public functions to execute the form validations inside the class file of Livewire. All the helper functions of Laravel are totally available in Livewire. Like _construct() function there is a render() function in the livewire class. Whenever the class file is called the render function is executed.

Type of variables used in Livewire class:

In Livewire class we must define all the variables. There are two types of variables. One is global variable which is responsible for instant data transaction between class and view component file. It is also used for parent-child component communication. The other type is local variable which is kept under specific function. This variables become active only when the respective function is called and these are not necessary to defined mandatorily. Here is some instances.

				
					<?php
namespace App\Livewire;
use App\Models\DocumentType;
use App\Models\Notice;
use Livewire\Component;
use Illuminate\Support\Arr;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class AddNotice extends Component
{
    public $date;
    public $title;
    public $type,$detail,$file;
    public $data = [];
    use WithFileUploads;
 
    protected $rules = [
        'date' =>'required|date',
        'title' => 'required|min:10',
        'type' => 'required',
        'detail' => 'required|min:20',
        'file' => 'required|mimes:jpeg,jpg,pdf|max:10000'
    ];
 
    public function storeNotice()
    {
 
        $input = $this->validate();
 
        $filename = Auth::user()->office->id.'.'.time().'.'.$input['file']->getClientOriginalExtension();
 
        $notice = Arr::except($input,['file'])+['file'=>$filename,'office_id'=>Auth::user()->office->id];
 
        if($this->file->storeAs('notices', $filename,'local') && Notice::create($notice))
        {
            $this->reset('date','title','type','detail');
            session()->flash('success', 'Notice created successfully.');
        }
        else
        {
            session()->flash('error','Something went wrong!!');
        }
    }
 
    public function render()
    {
        $types = DocumentType::all();
        $notices = Auth::user()->office->notices;
        return view('livewire.add-notice')->withNotices($notices)->withTypes($types);
    }
}
				
			
Here as we see the variables (in bold) $date, $title, $detail, $type, $data and $file are the global variables. To access the global variable inside the class or view “$this->” notion is used like following.
 
				
					$this->date, $this->detail
				
			

For array it would be like

				
					$this->data['name']
				
			
Variable initialization:
In case of array the variable we must define them as empty array. If there is some property or array key that are to be used, we must initialize the property like following
				
					public $data = [
['name' => ' ', 'address' => ' ']
];
				
			

The initialization is necessary because when the view component is rendered, if the variable property ‘name‘ and ‘address‘ is not assigned with a value by the user through the form input, the property will be nonexistent. Then the form validation rule will not be applicable and the validation will be malfunctioned. 

Again if it is necessary to dynamically add new rows of values of ‘name and ‘address’ property to variable $data, there must have to be a way or function which has to be called to initialize the properties with a default value. Otherwise if no value assigned the validation function will become confused and only the variables with default values will be under validation process. Remember the global variable always holds the values assigned to it whether it is done manually or dynamically. So if it is needed to change it with the change of any other input the variable must be reset or adjusted. This is very important specially for array variable.

Form Submission:
Unlike normal Laravel form submission, here in Livewire we don’t need to call route() through href property. In exchange in Livewire view component in the time of form submission we will use wire:submit.prevent=(method). This method is a function defined in the class file and responsible for actions after form submission. All the form validations and post submission processing are done in that function. Here all the processes are same as native Laravel form submission. The difference is that, here there we don’t need to call the Request helper function. In exchange we can access all the input values by using the global variable. Here is How
 
In the view component suppose we have an input field. Here in exchange of name property we will use wire:model=”global variable”. For an instance
				
					<form onsubmit="return confirm('Are you sure?')" wire:submit.prevent="storeNotice" >
   <input id="amount" wire:model="title"  type="text" class="form-control" required>
   <button type="submit" class="btn btn-primary">Submit</button>
 </form

				
			

Here the global variable $title is directly bound to the input field. Whenever the input field gets a value, the variable $title inside both view and class becomes updated. This is fun!!! All you have to do is call the storeNotice function by submitting the form and access the variable using $this->title in the class file for further actions. In the class file

				
					public function storeNotice()
{
      dd($this->title);
}
				
			

After processing there is no need to redirect or return to the view. That’s the magic of Livewire. Because like old JavaScript all the information get updated instantly.

Form Validation:
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
2
0
Would love your thoughts, please comment.x
()
x