Make counter app using livewire in laravel

In this tutorial i will show you how to make simple counter App . in this tutorial we can not using any database or any big logic it is

simple and easy to implements let see . we are using Livewire package for this counter app


composer create-project laravel/laravel larainfo 


after install our project we can use any css framework for looking good i use Boostrap 4 now let install livewire package


composer require livewire/livewire  

after that we need to put @livewireStyles and @livewireScripts in your main file

 <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    @livewireStyles
</head>


@livewireScripts
</body>
</html>

Create a component


php artisan make:livewire Counter

 

COMPONENT CREATED 🤙

CLASS: app/Http/Livewire/Counter.php

VIEW: resources/views/livewire/counter.blade.php


<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Counter extends Component
{
    public $counter;
    public $size;

    public function increment()
    {
        // $this->counter = $this->counter + $this->size;
        $this->counter += $this->size;
    }

    public function decrement()
    {
        $this->counter -= $this->size;
    }

    public function mount()
    {
        $this->counter = 0;
        $this->size = 1; //default value 
    }
    public function render()
    {
        return view('livewire.counter');
    }
}


now show home.blade.php


@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Counter</div>

                <div class="card-body">
                        @livewire('counter')
                </div>
            </div>
        </div>
    </div>
</div>
@endsection



@livewire('counter') or <livewire-counter/> both are work


VIEW: resources/views/livewire/counter.blade.php


<div>
    <p>{{ $counter }}</p>
    <div class="form-group">
    <input type="number" class="form-control" wire:model="size">
    </div>
    <button wire:click="increment" class="btn btn-info"> + </button> | <button wire:click="decrement" class="btn btn-info"> - </button>
</div>