Assignments Of Day 15 Pagination in Laravel

 

 Assignments Of Day 15

Pagination in Laravel

Assignment 1: Basic Pagination with Users

Task:

Create a simple pagination system that displays a list of users. The controller should fetch 5 users per page, and the Blade view should display the user data with pagination links.

Solution:

Controller:

php

Copy code

// UserController.php

public function index()

{

    // Fetch users with 5 per page

    $users = User::paginate(5);

   

    // Pass the users to the view

    return view('users.index', compact('users'));

}

Blade View (users/index.blade.php):

php

Copy code

<h1>User List</h1>

 

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $users->links() }}

</div>

Expected Outcome:

  • A list of users is displayed with 5 users per page.
  • Pagination links at the bottom allow navigation between pages.

Assignment 2: Pagination with Custom Per-Page Limit

Task:

Modify the previous example to allow the user to specify how many users to display per page. Use a dropdown list to choose between 5, 10, and 15 users per page. The pagination should update according to the selection.

Solution:

Controller:

php

Copy code

// UserController.php

public function index(Request $request)

{

    // Get the per-page value from the query string, default to 10

    $perPage = $request->input('per_page', 10);

 

    // Fetch users with dynamic per page value

    $users = User::paginate($perPage);

 

    // Pass the users to the view

    return view('users.index', compact('users', 'perPage'));

}

Blade View (users/index.blade.php):

php

Copy code

<h1>User List</h1>

 

<!-- Dropdown to select number of users per page -->

<form action="{{ route('users.index') }}" method="GET">

    <label for="per_page">Users per page:</label>

    <select name="per_page" id="per_page" onchange="this.form.submit()">

        <option value="5" {{ $perPage == 5 ? 'selected' : '' }}>5</option>

        <option value="10" {{ $perPage == 10 ? 'selected' : '' }}>10</option>

        <option value="15" {{ $perPage == 15 ? 'selected' : '' }}>15</option>

    </select>

</form>

 

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $users->appends(['per_page' => $perPage])->links() }}

</div>

Expected Outcome:

  • A dropdown allows the user to select how many users to display per page.
  • Pagination links adjust based on the selected number of users per page.

Assignment 3: Paginate with Sorting

Task:

Add sorting functionality to the user list. Allow the user to sort by name or email in ascending or descending order. The results should be paginated as well.

Solution:

Controller:

php

Copy code

// UserController.php

public function index(Request $request)

{

    // Get the per-page value and sorting direction

    $perPage = $request->input('per_page', 10);

    $sortBy = $request->input('sort_by', 'name'); // Default sorting by name

    $sortOrder = $request->input('sort_order', 'asc'); // Default sorting order

 

    // Fetch users, sorted by the specified column and direction

    $users = User::orderBy($sortBy, $sortOrder)->paginate($perPage);

 

    // Pass data to the view

    return view('users.index', compact('users', 'perPage', 'sortBy', 'sortOrder'));

}

Blade View (users/index.blade.php):

php

Copy code

<h1>User List</h1>

 

<!-- Sorting Form -->

<form action="{{ route('users.index') }}" method="GET">

    <label for="sort_by">Sort by:</label>

    <select name="sort_by" id="sort_by" onchange="this.form.submit()">

        <option value="name" {{ $sortBy == 'name' ? 'selected' : '' }}>Name</option>

        <option value="email" {{ $sortBy == 'email' ? 'selected' : '' }}>Email</option>

    </select>

 

    <label for="sort_order">Order:</label>

    <select name="sort_order" id="sort_order" onchange="this.form.submit()">

        <option value="asc" {{ $sortOrder == 'asc' ? 'selected' : '' }}>Ascending</option>

        <option value="desc" {{ $sortOrder == 'desc' ? 'selected' : '' }}>Descending</option>

    </select>

 

    <label for="per_page">Users per page:</label>

    <select name="per_page" id="per_page" onchange="this.form.submit()">

        <option value="5" {{ $perPage == 5 ? 'selected' : '' }}>5</option>

        <option value="10" {{ $perPage == 10 ? 'selected' : '' }}>10</option>

        <option value="15" {{ $perPage == 15 ? 'selected' : '' }}>15</option>

    </select>

</form>

 

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $users->appends(['sort_by' => $sortBy, 'sort_order' => $sortOrder, 'per_page' => $perPage])->links() }}

</div>

Expected Outcome:

  • Users can sort the list by name or email in either ascending or descending order.
  • The results are paginated and update dynamically based on sorting preferences.

Assignment 4: Paginate with Search Functionality

Task:

Implement a search feature where the user can search for users by name. The search results should be paginated.

Solution:

Controller:

php

Copy code

// UserController.php

public function index(Request $request)

{

    $perPage = $request->input('per_page', 10);

    $searchQuery = $request->input('search', '');

 

    // Fetch users based on search query

    $users = User::where('name', 'like', '%' . $searchQuery . '%')->paginate($perPage);

 

    return view('users.index', compact('users', 'perPage', 'searchQuery'));

}

Blade View (users/index.blade.php):

php

Copy code

<h1>User List</h1>

 

<!-- Search Form -->

<form action="{{ route('users.index') }}" method="GET">

    <input type="text" name="search" placeholder="Search by name" value="{{ $searchQuery }}">

    <button type="submit">Search</button>

   

    <label for="per_page">Users per page:</label>

    <select name="per_page" id="per_page" onchange="this.form.submit()">

        <option value="5" {{ $perPage == 5 ? 'selected' : '' }}>5</option>

        <option value="10" {{ $perPage == 10 ? 'selected' : '' }}>10</option>

        <option value="15" {{ $perPage == 15 ? 'selected' : '' }}>15</option>

    </select>

</form>

 

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $users->appends(['search' => $searchQuery, 'per_page' => $perPage])->links() }}

</div>

Expected Outcome:

  • Users can search for a name, and the results are displayed with pagination.
  • The search query is maintained across pagination links.

These assignments provide a solid practice for students to learn and apply pagination concepts in Laravel, including customizing the per-page limit, sorting, searching, and using pagination links.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more assignments based on Pagination in Laravel, along with solutions for each:


Assignment 5: Pagination with Multiple Models

Task:

Create a paginated list that displays both Users and Posts. Fetch and display data from two different models (e.g., User and Post), with pagination applied to both.

Solution:

Controller:

php

Copy code

// UserController.php

public function index()

{

    // Paginate users and posts, 5 items per page

    $users = User::paginate(5);

    $posts = Post::paginate(5);

 

    // Pass the paginated data to the view

    return view('users.index', compact('users', 'posts'));

}

Blade View (users/index.blade.php):

php

Copy code

<h1>User List</h1>

 

<!-- Display Users -->

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Users Pagination Links -->

<div class="pagination">

    {{ $users->links() }}

</div>

 

<h1>Post List</h1>

 

<!-- Display Posts -->

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Title</th>

            <th>Content</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($posts as $post)

            <tr>

                <td>{{ $post->id }}</td>

                <td>{{ $post->title }}</td>

                <td>{{ $post->content }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Posts Pagination Links -->

<div class="pagination">

    {{ $posts->links() }}

</div>

Expected Outcome:

  • Two separate paginated lists are displayed: one for users and another for posts.
  • Each list has its own pagination links for navigation.

Assignment 6: Add Pagination with Filters

Task:

Create a paginated list of Products. Add filtering functionality to allow users to filter products based on category and price. Display only the products that match the selected filters.

Solution:

Controller:

php

Copy code

// ProductController.php

public function index(Request $request)

{

    // Retrieve filters from query string

    $category = $request->input('category', null);

    $price = $request->input('price', null);

 

    // Start query builder

    $query = Product::query();

 

    // Apply category filter if provided

    if ($category) {

        $query->where('category', $category);

    }

 

    // Apply price filter if provided

    if ($price) {

        $query->where('price', '<=', $price);

    }

 

    // Paginate results with 10 products per page

    $products = $query->paginate(10);

 

    // Pass filters and paginated results to the view

    return view('products.index', compact('products', 'category', 'price'));

}

Blade View (products/index.blade.php):

php

Copy code

<h1>Product List</h1>

 

<!-- Filter Form -->

<form action="{{ route('products.index') }}" method="GET">

    <label for="category">Category:</label>

    <select name="category" id="category">

        <option value="">All Categories</option>

        <option value="electronics" {{ $category == 'electronics' ? 'selected' : '' }}>Electronics</option>

        <option value="clothing" {{ $category == 'clothing' ? 'selected' : '' }}>Clothing</option>

        <option value="books" {{ $category == 'books' ? 'selected' : '' }}>Books</option>

    </select>

 

    <label for="price">Price (max):</label>

    <input type="number" name="price" id="price" value="{{ $price }}">

 

    <button type="submit">Filter</button>

</form>

 

<!-- Display Products -->

<table>

    <thead>

        <tr>

            <th>Product Name</th>

            <th>Category</th>

            <th>Price</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($products as $product)

            <tr>

                <td>{{ $product->name }}</td>

                <td>{{ $product->category }}</td>

                <td>${{ $product->price }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $products->appends(['category' => $category, 'price' => $price])->links() }}

</div>

Expected Outcome:

  • Users can filter products by category and maximum price.
  • The paginated list of filtered products is displayed, and the pagination links update based on the selected filters.

Assignment 7: Implement Pagination in a Blog Application

Task:

Create a simple blog application with a paginated list of Posts. Each post should show the title, content (excerpt), and a "Read More" button linking to a single post's detail page.

Solution:

Controller:

php

Copy code

// BlogController.php

public function index()

{

    // Fetch all posts, 5 posts per page

    $posts = Post::paginate(5);

 

    return view('blog.index', compact('posts'));

}

Blade View (blog/index.blade.php):

php

Copy code

<h1>Blog Posts</h1>

 

<!-- Display Posts -->

@foreach ($posts as $post)

    <div class="post">

        <h2>{{ $post->title }}</h2>

        <p>{{ Str::limit($post->content, 100) }}</p>

        <a href="{{ route('blog.show', $post->id) }}">Read More</a>

    </div>

@endforeach

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $posts->links() }}

</div>

Single Post Controller:

php

Copy code

// BlogController.php

public function show($id)

{

    $post = Post::findOrFail($id);

    return view('blog.show', compact('post'));

}

Blade View for Single Post (blog/show.blade.php):

php

Copy code

<h1>{{ $post->title }}</h1>

<p>{{ $post->content }}</p>

Expected Outcome:

  • The home page displays a list of posts, each with an excerpt and "Read More" link.
  • Pagination links allow users to navigate between pages of posts.
  • Clicking on "Read More" takes the user to the detailed view of the selected post.

Assignment 8: Paginate Comments for a Post

Task:

For the blog application in the previous assignment, add a feature to paginate comments under each post. Each post should show the latest 5 comments, and older comments can be accessed via pagination links.

Solution:

Controller:

php

Copy code

// BlogController.php

public function show($id)

{

    $post = Post::findOrFail($id);

 

    // Paginate comments (5 comments per page)

    $comments = $post->comments()->paginate(5);

 

    return view('blog.show', compact('post', 'comments'));

}

Blade View for Single Post (blog/show.blade.php):

php

Copy code

<h1>{{ $post->title }}</h1>

<p>{{ $post->content }}</p>

 

<h2>Comments</h2>

 

<!-- Display Comments -->

@foreach ($comments as $comment)

    <div class="comment">

        <p><strong>{{ $comment->user->name }}</strong>: {{ $comment->content }}</p>

    </div>

@endforeach

 

<!-- Pagination Links for Comments -->

<div class="pagination">

    {{ $comments->links() }}

</div>

Expected Outcome:

  • For each post, comments are displayed with pagination.
  • Only the most recent 5 comments are shown, with the ability to navigate to older comments via pagination.

Assignment 9: Paginate and Search Articles by Title

Task:

Create an article list page with a search form that allows users to search for articles by title. The list should be paginated, and the search results should update dynamically.

Solution:

Controller:

php

Copy code

// ArticleController.php

public function index(Request $request)

{

    $searchQuery = $request->input('search', '');

 

    // Fetch articles where title matches the search query

    $articles = Article::where('title', 'like', '%' . $searchQuery . '%')->paginate(10);

 

    return view('articles.index', compact('articles', 'searchQuery'));

}

Blade View (articles/index.blade.php):

php

Copy code

<h1>Article List</h1>

 

<!-- Search Form -->

<form action="{{ route('articles.index') }}" method="GET">

    <input type="text" name="search" placeholder="Search by title" value="{{ $searchQuery }}">

    <button type="submit">Search</button>

</form>

 

<!-- Display Articles -->

@foreach ($articles as $article)

    <div class="article">

        <h2>{{ $article->title }}</h2>

        <p>{{ $article->content }}</p>

    </div>

@endforeach

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $articles->appends(['search' => $searchQuery])->links() }}

</div>

Expected Outcome:

  • Users can search articles by title, and the results are paginated.
  • The search query is preserved when navigating through the paginated results.

These assignments give students extensive practice with pagination in various real-world scenarios, reinforcing how to implement pagination in Laravel applications.


Comments

Popular posts from this blog

Lecture Notes Of Day 24: Laravel Policies

MCQs Of Day CRUD 8 Operations with Eloquent

MCQs of Day 7 Eloquent ORM Basics