rafitio
rafitio

Reputation: 568

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')}}

Upvotes: 2

Views: 2848

Answers (2)

Illia Yaremchuk
Illia Yaremchuk

Reputation: 2025

Use Eloquent: Relationships

For example:

News.php model

class News extends Model
    {
        protected $primaryKey = 'id';

        function withCategories() {
       return $this->hasOne('App\Categories', 'id', 'category_id');
    }

    public function list(){
         News::with('withCategories')->orderBy('created_at', 'DESC')
    ->paginate(10);
    }
}

in news.blade.php (example)

<table>
<tbody>
@foreach ($news as $news)
<tr>
<th>{{ $news->id }}</th>
<td>{{ $news->title }}</td>
<td>{{ $news->withCategories->title }}</td> <!-- Category name-->
</tr>
@endforeach
</tbody>
</table>
</div>

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35367

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);

Upvotes: 4

Related Questions