My First Laravel LiveWire Component

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{

    public $message;

    public function render()
    {
        return view('livewire.hello-world');
    }
}

 Install or check package.json to see if the Livewire package is installed

composer require livewire/livewire

Add LiveWire CSS and Javascript files by putting the fol

@livewireStyles btween <head> and </head>

and 

@livewireScripts near the closing </body>

 

Create your first LiveWire component by running the following command

$ php artisan make:livewire HelloWorld

This will create two files, the class and the view.

app/Http/Livewire/HelloWorld.php

resources/views/livewire/hello-world.blade.phpYou can then add this component to any blade file as a directive
 

@livewire('hello-world') 

We can pass the component a string by adding a variable in the component's class

 update

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{

    public $message;

    public function render()
    {
        return view('livewire.hello-world');
    }
}

update resources/views/livewire/hello-world.blade.php

 

<div>
    <h1>{{ $message }}</h1>
</div>

 update the directive to and pass the message

@livewire('hello-world', ['message' => 'Hello World']) 

You can also do it in class
 

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{

    public $message = "Hello World";

    public function render()
    {
        return view('livewire.hello-world');
    }
}

or

 

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{

    public $message;

    public function render()
    {

        $this->message = "Hello World";
        return view('livewire.hello-world');
    }
}

You don't even need to render function if you are just passing values

 

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{
    public $message = "Hello World";
}

that's kind of cool

 

Making the Laravel Livewire component dynamic with a form


Find the blade Livewire template file

resources/views/livewire/hello-world.blade.php

add an input form

<div>
    {{-- The Master doesn't talk, he acts. --}}

    <div>
        <input wire:model="message" type="text">
     
        <h1>{{ $message }}</h1>
    </div>
</div>

Let's update the Livewire component as well to an earlier version

app/Http/Livewire/HelloWorld.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class HelloWorld extends Component
{

    public $message;

    public function render()
    {

        return view('livewire.hello-world');
    }
}