Quickstart
- Install Livewire
- Create a component
- Include the component
- View it in the browser
- Add "counter" functionality
- View it in the browser
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:some-component />
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:
1class Counter extends Component 2{ 3 public $count = 0; 4 5 public function increment() 6 { 7 $this->count++; 8 } 9 10 public function render()11 {12 return view('livewire.counter');13 }14}
1<div style="text-align: center">2 <button wire:click="increment">+</button>3 <h1>{{ $count }}</h1>4</div>
View it in the browser
Now reload the page in the browser, you should see the counter
component rendered. If you click the "+" button, the page should automatically update without a page reload. Magic 🧙♂.️