[Vuejs]-Laravel 9 Vue js 3 Pagination

0👍

It seems you try to handle all the pagination logic from the client side but you get only 3 items from your controller with the take(3) so it couldn’t works.

You should send the currentPage and the itemsPerPage to your controller, and refresh the data when prevPage() and nextPage() are called.

You could do something like this (not tested it, just to give an idea) :

Controller :

public function getData(Request $request)
{
    $currentPage = $request->input('currentPage');
    $itemsPerPage = $request->input('itemsPerPage');
    $list_lowongan = Lowongan::orderBy('id', 'desc')
        ->skip(($currentPage >= 1 ? $currentPage -1 : 0) * $itemsPerPage)
        ->take($itemsPerPage)
        ->get();

    return response()->json([
        'items' => $list_lowongan,
        'totalPages' => round(Lowongan::count() / $itemsPerPage)
    ]);
}

Vue component :

...
data() {
    return {
        list_lowongan: [],
        currentPage: 1,
        itemsPerPage: 3,
        totalPages: 1
    };
},
async mounted() {
    await this.getData()
},
methods: {
    async getData() {
        try {
            let res = await axios.get('lowongan/list', {
                params: {
                    currentPage: this.currentPage,
                    itemsPerPage: this.itemsPerPage,
                }
            })
            this.totalPages = res.data.totalPages
            this.list_lowongan = res.data.items
        }catch (e) {
            console.log(e)
        }
    },
    async prevPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            await this.getData()
        }
    },
    async nextPage() {
        if (this.currentPage < this.totalPages) {
            this.currentPage++;
            await this.getData()
        }
    }
},
 ...

Laravel has pagination support…

Leave a comment