Livewire Posts

Implement Bootstrap Laravel Livewire tables

It's 2022 and people are still using the old jquery tables with Laravel. As laravel have the livewire why do we have to use the jquery tables ??

In this tutorial, we are going to use the livewire tables and gonna see the benefits of it.

The main problem I see with Jquery Datatable is :

  • Page will flicker when we do any search, as it will fire the server-side query and fetch results
  • HTML Appending into JS for action column
  • It's not easy to customize the row, we have to write the HTML into JS

The main benefits of using Laravel Livewire tables are:

  • After searching results will be quickly updated on-page, without flickering
  • As the Livewire table is JS less, Of course, you don't have to append HTML into it. you can do it via blade files :)
  • You can easily customize the row and tables view by adding your custom blade views.

How to integrate Bootstrap Livewire tables?

For that we are going to use the following package :

https://github.com/rappasoft/laravel-livewire-tables

Install Package

composer require rappasoft/laravel-livewire-tables

Publish Assets

php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-config

php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-views

php artisan vendor:publish --provider="Rappasoft\LaravelLivewireTables\LaravelLivewireTablesServiceProvider" --tag=livewire-tables-translations `

Choosing Bootstrap 5 theme

Into the published config file you can choose/change theme to bootstrap-5

    return [
        /**
        * Options: tailwind | bootstrap-4 | bootstrap-5.
        */
        'theme' => 'bootstrap-5',
    ];

Render the components

    <livewire:members-table />

Create Component

    namespace App\Http\Livewire;

    use App\Models\User;
    use Rappasoft\LaravelLivewireTables\DataTableComponent;
    use Rappasoft\LaravelLivewireTables\Views\Column;

    class MembersTable extends DataTableComponent
    {
        protected $model = User::class;

        public function configure(): void
        {
            $this->setPrimaryKey('id');
        }

        public function columns(): array
        {
            return [
                Column::make('ID', 'id')
                    ->sortable(),
                Column::make('Name')
                    ->sortable(),
            ];
        }
    }

That's It :)

That's it, and you will see the bootstrap-5 Laravel livewire table. it have other lot's of fucntionality too, you can use or disable it as per your need.

July 04, 20222 minutesVishal RibdiyaVishal Ribdiya
Make fully configurable livewire searching component

Nowadays, laravel livewire is becoming more trendy for geeks. as most developers are using it, more and more issues are facing while developing the products. one of them is searching the records.

Recently we have developed the livewire common searchable component which makes your searching easier, as you can specify which fields you want to search by just giving the field name into the component.

What you have to do is just create a SearchableComponent class into your App\Http\Livewire directory. just copy the following class on the given namespace.

<?php
namespace App\Http\Livewire;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Livewire\Component;
use Livewire\WithPagination;
use Str;

abstract class SearchableComponent extends Component
{
    use WithPagination;

    /**
      @var string
     /
    public $search = '';

    /**
      @var int
     /
    protected $paginate = 12;

    /* @var Builder /
    private $query;

    /**
      SearchableComponent constructor.

      @param $id
     /
    public function construct($id)
    {
        parent::construct($id);

        $this->prepareModelQuery();
    }

    /
       Prepare query
     /
    private function prepareModelQuery()
    {
        / @var Model $model */
        $model = app($this->model());

        $this->query = $model->newQuery();
    }

    /**
      @return mixed
     /
    abstract function model();

    /**
      Reset model query
     /
    protected function resetQuery()
    {
        $this->prepareModelQuery();
    }

    /**
      @return Builder
     /
    protected function getQuery()
    {
        return $this->query;
    }

    /**
      @param  Builder  $query
     /
    protected function setQuery(Builder $query)
    {
        $this->query = $query;
    }

    /**
      @param  bool  $search
      @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    protected function paginate($search = true)
    {
        if ($search) {
            $this->filterResults();
        }

        $all = $this->query->paginate($this->paginate);
        $currentPage = $all->currentPage();
        $lastPage = $all->lastPage();
        if ($currentPage > $lastPage) {
            $this->page = $lastPage;
        }

        return $this->query->paginate($this->paginate);
    }

    /**
      @return Builder
     /
    protected function filterResults()
    {
        $searchableFields = $this->searchableFields();
        $search = $this->search;

        $this->query->when(! empty($search), function (Builder $q) use ($search, $searchableFields) {
            $searchString = '%'.$search.'%';
            foreach ($searchableFields as $field) {
                if (Str::contains($field, '.')) {
                    $field = explode('.', $field);
                    $q->orWhereHas($field[0], function (Builder $query) use ($field, $searchString) {
                        $query->whereRaw("lower($field[1]) like ?", $searchString);
                    });
                } else {
                    $q->orWhereRaw("lower($field) like ?", $searchString);
                }
            }
        });

        return $this->query;
    }

    /**
      @return mixed
     /
    abstract function searchableFields();
}

Now you have to extend your existing Laravel component by SearchableComponent. Let's say we already have the Tags livewire component. and it looks like the following.

App\Http\Livewire;

use App\Models\Tag;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class Tags extends SearchableComponent
{
    public function render()
    {
        $tags = $this->searchTags();

        return view('livewire.tags', [undefined])->with("search");
    }

    /**
      @return LengthAwarePaginator
     /
    public function searchTags()
    {
        $this->setQuery($this->getQuery());

        return $this->paginate();
    }

    function model()
    {
        return Tag::class;
    }

    function searchableFields()
    {
        return [
];
    }
}

So here we have extended our existing Tags component by SearchingComponent.

In searchable fields, you can specify the field name that you want to search. and replace the Model with your records Modal.

That's it. Now you don't need to write search queries again and again. just extend your livewire component by a searchable component.

Here are some Interesting livewire tutorials that you need to check :

October 22, 20201 minuteVishal RibdiyaVishal Ribdiya
How to use select2 with livewire

Most of the developers are facing a select2 style removing issue when livewire renders the component.

We can resolve this issue by using a livewire javascript hook.

Here is my screen with select2 before livewire component rendering.

2020-12-10_5fd2207b2f583

And when the livewire component is refreshed means re-render the select2 style is gone ☹️

2020-12-10_5fd221ec084b8

How to Fix it ?? 🤔

Well, you just need to add some JQuery code to your livewire component. Here we are going to use afterDomUpdate webhook of livewire. add the following code to your livewire component :

document.addEventListener('livewire:load', function (event) {
   window.livewire.hook('afterDomUpdate', () => {         
   $('#select2ID').select2();     
   }); 
});

livewire:load is listening events when the livewire component is loaded and we can add our code within it.

And now when your livewire component is refreshed your select2 style will be still there as we are again applying it.

Other Livewire Posts:

Stay tuned to us for more interesting stuff about livewire.

September 03, 20201 minuteVishal RibdiyaVishal Ribdiya
Setup Laravel Livewire with Basic Component Example

Laravel Livewire is used to build dynamic web pages that work without ajax or any javascript code. We can build dynamic components with livewire with less code and more functionalities.

I hope this basic introduction will be enough to start laravel livewire.

Now let's move to the installation steps, and I hope you already have set up your laravel project.

Install Livewire

 composer require livewire/livewire 

Include the javascript and styles (On your master blade file)

  ...      
@livewireStyles   

   ...
     @livewireScripts

Create Your Component

Here we are going to create a component to create a summation of 2 values without hitting any buttons, it will do a summation of 2 values as you type in text boxes.

Now let's create our component by hitting the following command :

php artisan make:livewire Summation

it will create 2 files as shown below:

// app/Http/Livewire/Summation/php
namespace App\Http\Livewire;

use Livewire\Component;

class Summation extends Component
{
    public function render()
    {
        return view('livewire.summation');
    } 
}

// resources/views/livewire/summation.blade.php

Include the component

Include the created component to your view where you want to show.

    ...
    @livewireStyles

    ...

    @livewireScripts

Now let's first do a change in our livewire component Summation.php

namespace App\Http\Livewire;

use Livewire\Component;

class Summation extends Component
{ 
   public $value1 = 0;
   public $value2 = 0;
   public $sum = 0;

   public function mount()
   {
      $this->sum = 0;
   }

   public function render()
   {
      $this->sum = $this->value1 + $this->value2;

      return view('livewire.summation');
   }
 }

Here we have to take 2 public properties value1, value2, and sum. and in the mounting method (which will be called when the page is loaded the first time) I have replaced the sum property value to 0.

And In the render method, I have done a summation of the 2 public property values. which will be directly accessed values of input from blade files directly here. but how ?? we will see soon.

Now let's change the livewire blade component.

  

Here we have bound all properties by using wire:model. so as we will type in input box 1 it will be directly accessed by $value1 into the component.

and the property $sum will be changed as we change the input box values.

So that's how cool livewire is. you can create different dynamic components as you need by using livewire.

Stay tuned to read more interesting posts on livewire.

August 07, 20202 minutesVishal RibdiyaVishal Ribdiya