voiceinthedark's avatar

Capturing the Pagination links in AlpineJs

I have a searchbar component which available on many pages, when user input a string, I populate the result and dispatch it as a browser event, then capture it in my view. My problem is that I want to paginate the result by providing a next and previous pages buttons on the search dropdown; How can I capture the pagination links in Alpinejs?

Here is my code:

// searchbar.php component
// ...
public function search($value){
        $this->search = $value;

        $this->results = Post::search($this->search)->paginate(5);
        $this->dispatchBrowserEvent('search', ['results' => $this->results]);
    }

And here is my view:

// search-bar.blade.php
<div class="self-center px-4" x-data="{ dropdownOpen: false, results: [] }">
    <x-input-wireui icon="search" placeholder="Search for posts" class="text-gray-900"
        x-on:input.debounce.500ms="Livewire.emitTo('search.search-bar', 'searchValueChange', $event.target.value)"
        x-on:search.window="results = $event.detail.results.data"
        x-on:click="dropdownOpen = !dropdownOpen">

    </x-input-wireui>

    <div x-show="dropdownOpen" class="relative" >
        <div class="absolute left-0 z-20 w-[500px] rounded-lg shadow-lg shadow-slate-500 bg-white divide-y-2 divide-gray-400 divide-dotted">
            <template  x-for="post in results">
                <div class="flex flex-col py-2">
                    <div class="py-4 mx-2 mt-2 text-sm hover:bg-gray-200" x-text="post.title"></div>
                    <div class="px-4 mx-2" x-text="(post.content).substring(0, 20)"></div>
                </div>
            </template>
        </div>
    </div>

</div>
0 likes
2 replies
MohamedTammam's avatar

You can access your pagination data from you paginated model.

For example, if you have

$posts = Post::paginate();

Then you can use $posts to access pagination data. You can find pagination properties here: https://laravel.com/docs/10.x/pagination#paginator-instance-methods

Because your search in many pages, you might have a conflict having two paginated Livewire components at the same page. Here's how you can solve that: https://laravel-livewire.com/docs/2.x/pagination#multiple-paginators

voiceinthedark's avatar

@MohamedTammam Unfortunately that didn't work for me since I am sending a Livewire paginator, I solved it by sending the entire result query and created my own paginator in javascript and fed it to alpine data.

Please or to participate in this conversation.