Setup Laravel Livewire with Basic Component ExampleLaravel
November 25, 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 installation steps, and I hope you already have setup your laravel project.

Install Livewire

 composer require livewire/livewire

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

  ...
     @livewireStyles
  </head>
  <body>
  ...

     @livewireScripts
  </body>
  </html>

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
<div>
    ...
</div>

Include the component

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

 <head>
    ...
    @livewireStyles
 </head>
 <body>
    <livewire:summation />

    ...

    @livewireScripts
 </body>
 </html>

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 mount method (which will be called when the page is load 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.

  <div>
   <input type="text" class="" wire:model="value1">

    <input type="text" class="" wire:model="value2">

    <input type="text" disabled wire:model="sum">
  </div>

Here we have bind 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 of a livewire.