Implementing pagination in a Laravel and Vue.js application involves a combination of backend and frontend code. Laravel provides built-in support for pagination, and Vue.js can be used to handle the frontend components and interactions. Here's a step-by-step guide:
Install Laravel: If you haven't already, create a new Laravel project using Composer.
bashcomposer create-project --prefer-dist laravel/laravel your-project-name
Create a Model and Migration: Create a model and migration for the data you want to paginate.
bashphp artisan make:model Post -m
Run Migration: Run the migration to create the database table.
bashphp artisan migrate
Seeder (Optional): Optionally, you can create a seeder to populate your database with sample data.
bashphp artisan make:seeder PostsTableSeeder
Controller: Create a controller to handle pagination logic.
bashphp artisan make:controller PostController
In your PostController
, use the paginate
method to fetch paginated data.
php// app/Http/Controllers/PostController.php
use App\Models\Post;
public function index()
{
$posts = Post::paginate(10); // Change 10 to the desired number of items per page
return response()->json($posts);
}
Install Vue: Install Vue.js using npm or yarn.
bashnpm install vue
Create Vue Component: Create a Vue component to display paginated data.
bashvue create your-vue-app
Axios: Install Axios for making HTTP requests from your Vue.js app.
bashnpm install axios
Vue Component: In your Vue component, fetch and display paginated data.
html<!-- src/components/PostList.vue -->
<template>
<div>
<div v-for="post in posts" :key="post.id">
{{ post.title }}
</div>
<nav>
<ul class="pagination">
<li v-if="posts.prev_page_url">
<a @click="fetchData(posts.prev_page_url)">Previous</a>
</li>
<li v-if="posts.next_page_url">
<a @click="fetchData(posts.next_page_url)">Next</a>
</li>
</ul>
</nav>
</div>
</template>
<script>
export default {
data() {
return {
posts: {},
};
},
mounted() {
this.fetchData('/api/posts'); // Adjust the API endpoint
},
methods: {
fetchData(url) {
axios.get(url).then(response => {
this.posts = response.data;
});
},
},
};
</script>
<style scoped>
/* Add your styles here */
</style>
Integration: Integrate the Vue component into your main Blade view or wherever you want it to appear.
html<!-- resources/views/welcome.blade.php -->
<div id="app">
<post-list></post-list>
</div>
<script src="{{ asset('js/app.js') }}"></script>
npm run dev
or npm run watch
after making changes to your Vue components.With these steps, you should have a basic pagination setup for your Laravel and Vue.js application.