Search code examples
laravelturbolinkslaravel-livewire

Weird Livewire + Turbolinks behavior


I'm building an admin panel in TALL (Laravel 7) + Turbolinks. One section only includes a Livewire component that shows a paginated table of Product elements and a search field (the only "strange" thing that I'm doing before this is injecting a Market model instance to the request in a middleware).

The problem arises when I go to /products route where is the livewire component included nothing works... The records of the first page are fine, but pagination links are dead and search field does nothing, no console errors, no livewire errors, it's like javascript is not working at all, and here's the strangest thing: if I reload the page, the Market data I loaded in middleware is added to the query string and everything starts working as intended.

Middleware:

public function handle($request, Closure $next) {
    $market = Market::findOrFail(session('selected_market'));
    $request->request->add(['market' => $market]);
    return $next($request);
}

Livewire Component:

class ProductsTable extends Component{
    use WithPagination;

    public $search = '';
    protected $queryString = [
        'search' => ['except' => ''],
        'page' => ['except' => 1],
    ];

    public function render(){
        $products = Product::where('market_id', request('market')->id)
        ->when($this->search !== '', function($query) {
            $query->where('name', 'like', "%{$this->search}%");
            $query->orWhere('brand', 'like', "%{$this->search}%");
        })->paginate(15);

        return view('livewire.products-table', ['products' => $products]);
    }
}

Livewire Component View:

<input wire:model.debounce.500ms="search" type="search" name="search" id="search">

<table>
    @forelse($products as $product)
        <tr onclick="Turbolinks.visit('{{ route('product', $product->id) }}')">
            <td>{{ $product->name }}</td>
            ...
        </tr>
    @empty
        <tr><td>Nothing to show for {{ $search }}</td></tr>
    @endforelse
</table>

{{ $products->links() }}

I'm really confused and tired with this, I have no clue what is going on and similar questions haven't been answered clearly.

Thanks


Solution

  • The solution was as simple as adding this to your scripts:

    document.addEventListener("turbolinks:load", function(event) {
      window.livewire.restart();
    });