Quickstart
Install Livewire
Include the PHP.
1composer require livewire/livewire
Include the JavaScript (on every page that will be using Livewire).
1...2 @livewireStyles3</head>4<body>5 ...6 7 @livewireScripts8</body>9</html>
Create a component
Run the following command to generate a new Livewire component called counter
.
1php artisan make:livewire counter
Running this command will generate the following two files:
1namespace App\Http\Livewire; 2 3use Livewire\Component; 4 5class Counter extends Component 6{ 7 public function render() 8 { 9 return view('livewire.counter');10 }11}
1<div>2 ...3</div>
Let's add some text to the view so we can see something tangible in the browser.
1<div>2 <h1>Hello World!</h1>3</div>
Include the component
Think of Livewire components like Blade includes. You can insert @livewire
anywhere in a Blade view and it will render.
1<head> 2 ... 3 @livewireStyles 4</head> 5<body> 6 @livewire('counter') 7 8 ... 9 10 @livewireScripts11</body>12</html>
View it in the browser
Load the page you included Livewire on in the browser. You should see "Hello World!".
Add "counter" functionality
Replace the generated content of the counter
component class and view with the following:
1use Livewire\Component; 2 3class Counter extends Component 4{ 5 public $count = 0; 6 7 public function increment() 8 { 9 $this->count++;10 }11 12 public function decrement()13 {14 $this->count--;15 }16 17 public function render()18 {19 return view('livewire.counter');20 }21}
1<div style="text-align: center">2 <button wire:click="increment">+</button>3 <h1>{{ $count }}</h1>4 <button wire:click="decrement">-</button>5</div>
View it in the browser
Now reload the page in the browser, you should see the counter
component rendered. If you click the "+" or "-" button, the page should automatically update without a page reload. Magic 🧙♂.️