Home / Snippets / Getting Started With Laravel Livewire
Getting Started With Laravel Livewire cover

Getting Started With Laravel Livewire

420

2 years ago

0 comments

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>
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this