rafitio rafitio - 28 days ago 18
PHP Question

Laravel pagination at leftjoin

I want to create leftjoin with pagination on laravel.
how to create pagination with leftjoin ?

Here my code :

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
->select('news.*' ,'categories.category')
->get()->sortByDesc('created_at');


Previously, i use
$news = News::paginate(10);
and its works, but it without leftjoin.

and here my html code to create pagination

{{$news->links('vendor.pagination.pagination')}}

Answer

The paginate function should be done on the Query Builder object, not on the collection returned by get().

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
        ->select('news.*' ,'categories.category')
        ->paginate(10);

The same goes for sorting. When you call get()->sortByDesc(), you are getting a Collection then sorting the collection through PHP. Normally, you would want to use orderBy() in the query builder to sort through SQL.

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
        ->select('news.*' ,'categories.category')
        ->orderBy('created_at', 'DESC')
        ->paginate(10);