Monday, December 31, 2018

How to Hide Pagination Link While Not Using Paginate() Method in Laravel

How to Hide Pagination Link While Not Using Paginate() Method in Laravel

Pagination in Laravel is so easy and powerful. Yet there is a problem that cause an error.

Considering a situation that two methods send result sets to the same view file, one is generated by the paginate() method and one isn’t. However, the pagination links() results in an error while the result set is not generated from the paginate() method. How to solve this issue? If we can test whether the result set is generated from the paginate() method in the controller, the problem can be solved.

controller: ProductsController.php

class ProductController extends Controller
{
public function index()
  {
    $products = Product::paginate(5);
    return view('products.index', compact('products'));
  }

public function search(Request $request)
  {
    $request->validate([
      'keyword' => 'required'
    ]);
    $keyword = $request->get('keyword'); 
    $products = Product::where('prod_name', 'like', '%'.$keyword.'%')
      ->orWhere('prod_desc', 'like', '%'.$keyword.'%')->get();
    return view('products.index', compact('products'));
  }
}

view: index.blade.php (before)

    :
<div class="pagination justify-content-center">
  {{ $products->links() }}
</div> 
    :

If the result set is an instance of the class \Illuminate\Pagination\LengthAwarePaginator, then we can make sure that the result set is generated from the method paginate(). Therefor, a pagination link method is required in the view file. On the other hand, if the result set is not the instance of the class mentioned before, then the pagination link should be hidden. Thus, an if() statement is added to the view file as follows:

index.blade.php (after)

@if ($products instanceof \Illuminate\Pagination\LengthAwarePaginator)
  <div class="pagination justify-content-center">
	  {{ $products->links() }}
  </div> 
@endif

It solves the problem!

1 comment:

  1. How to Make Money at PokerStars in 2021 - Work
    What are titanium wire the differences between 바카라사이트 PokerStars and other poker 벳 인포 sites? — PokerStars 먹튀 has more than 80 งานออนไลน์ games from the classic game of PokerStars.

    ReplyDelete