Setup Laravel Livewire with Basic Component Example

Laravel
August 07, 20202 minutesuserVishal Ribdiya
Setup Laravel Livewire with Basic Component Example

Laravel Livewire is used to build dynamic web pages that work without ajax or any javascript code. We can build dynamic components with livewire with less code and more functionalities.

I hope this basic introduction will be enough to start laravel livewire.

Now let's move to the installation steps, and I hope you already have set up your laravel project.

Install Livewire

 composer require livewire/livewire 

Include the javascript and styles (On your master blade file)

  ...      
@livewireStyles   

   ...
     @livewireScripts

Create Your Component

Here we are going to create a component to create a summation of 2 values without hitting any buttons, it will do a summation of 2 values as you type in text boxes.

Now let's create our component by hitting the following command :

php artisan make:livewire Summation

it will create 2 files as shown below:

// app/Http/Livewire/Summation/php
namespace App\Http\Livewire;

use Livewire\Component;

class Summation extends Component
{
    public function render()
    {
        return view('livewire.summation');
    } 
}

// resources/views/livewire/summation.blade.php

Include the component

Include the created component to your view where you want to show.

    ...
    @livewireStyles

    ...

    @livewireScripts

Now let's first do a change in our livewire component Summation.php

namespace App\Http\Livewire;

use Livewire\Component;

class Summation extends Component
{ 
   public $value1 = 0;
   public $value2 = 0;
   public $sum = 0;

   public function mount()
   {
      $this->sum = 0;
   }

   public function render()
   {
      $this->sum = $this->value1 + $this->value2;

      return view('livewire.summation');
   }
 }

Here we have to take 2 public properties value1, value2, and sum. and in the mounting method (which will be called when the page is loaded the first time) I have replaced the sum property value to 0.

And In the render method, I have done a summation of the 2 public property values. which will be directly accessed values of input from blade files directly here. but how ?? we will see soon.

Now let's change the livewire blade component.

  

Here we have bound all properties by using wire:model. so as we will type in input box 1 it will be directly accessed by $value1 into the component.

and the property $sum will be changed as we change the input box values.

So that's how cool livewire is. you can create different dynamic components as you need by using livewire.

Stay tuned to read more interesting posts on livewire.