Posts Learn Components Snippets Categories Tags Tools About
/

Getting Started With Laravel Livewire

Let's get started with Laravel Livewire and make your Laravel application more reactive and dynamic

Created on Oct 18, 2021

403 views

In this short snippet, we'll get started with running Livewire on an existing Laravel project.

Step 1: Install Laravel Livewire


To install Laravel Livewire you can make use of the composer package manager.
composer require livewire/livewire

Step 2: Define The Livewire Styles and Scripts
Next, you have to define the livewire styles and scripts on the HTML head and body tag.

<!doctype html>
<html>
<head>
  <!-- ... -->
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link href="/tailwind.css" rel="stylesheet">

  @livewireStyles
</head>
<body>
  <!-- ... -->
  @livewireScripts
</body>
</html>

Optional: Publish Config and Front-end Assets


If you want to publish the configuration which contains the settings for Livewire namespace, layouts and etc you can run the command below.
php artisan livewire:publish --config
For the assets, you can make use of this command.
php artisan livewire:publish --assets
It's also highly recommended to specify the above command in composer.json file to automatically update it when new version is available.
{
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi",
            "@php artisan vendor:publish --force --tag=livewire:assets --ansi"
        ]
    }
}

Step 3: Create Simple Livewire Counter Component


You can create a simple component using the "livewire:make" command. For this example, we'll be using the Tailwind CSS component for the front-end UI.
php artisan make:livewire counter
The content of the Component should be as follows.
<?php

class Counter extends Component
{
    public $count = 0;

    public function increment()
    {
        $this->count++;
    }

    public function render()
    {
        return view('livewire.counter');
    }
}
The content of the "counter" views component will be:
<div style="text-align: center">
    <button wire:click="increment">+</button>
    <h1>{{ $count }}</h1>
</div>

Update the Laravel Blade Code


Now you can reference the Livewire counter component using the livewire tag like below.
<!doctype html>
<html>
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link href="/tailwind.css" rel="stylesheet">

  @livewireStyles
</head>
<body>
  <livewire:counter /> 

  @livewireScripts
</body>
</html>

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Getting Started With Laravel Livewire

)