DolDurma
DolDurma

Reputation: 17360

Laravel using paginate for relationship data

in my web application each content as posts belong to one or many category and categories has many posts, now when i fetch data from with this code:

$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);

that's return this output:

    LengthAwarePaginator {#971 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#963 ▼
        #items: array:1 [▼
          0 => ContentCategories {#862 ▼
            #table: "contents_categories"
            ...
            #attributes: array:6 [▶]
            #original: array:6 [▶]
            ...
            #relations: array:1 [▼
              "contents" => Collection {#962 ▼
                #items: array:2 [▼
                  0 => Contents {#952 ▶}
                  1 => Contents {#953 ▶}
                ]
              }
            ]
            ...
          }
        ]
      }
      #perPage: 10
      #currentPage: 1
      #path: "http://127.0.0.1:8000/category/5"
      #query: []
      #fragment: null
      #pageName: "page"
    }

in this paginator i'm trying to show contents array on view by this code:

@foreach($categoryContents->contents_categories->contents as $content)

@endforeach

but i get this error:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$contents_categories

how can i show this structure on paginator?

my models:

class ContentCategories extends Model
{
    ...

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

class Contents extends Model
{
    ...

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}

Upvotes: 1

Views: 6140

Answers (2)

DevK
DevK

Reputation: 9962

This query:

$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);

doesn't make a whole lot of sense. You're querying for a ContentCategory by id, which will match exactly 1 result, but you're still using latest(), which orders (nothing to order on 1 row) the results and calling paginate(10), which will paginate the result (nothing to paginate on 1 row).

You want to paginate the contents, not the parent ContentCategories:

// whereHas to scope it only to the category with id = `$id`
$contents = Contents::whereHas('categories', function ($subQuery) use ($id) {
        $subQuery->where('id', $id);
    })
    // Order the cotnents
    ->latest()
    // Paginate the contents
    ->paginate(10);

Then pass the $contents to your view and foreach over it:

@foreach($contents as $content)

@endforeach

Upvotes: 1

ali
ali

Reputation: 862

you can solve this issue as the following:

  $categoryContents = ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
    $categoryContents->getCollection()->transform(function ($item) {
        return $item->contents;
    });

Upvotes: 0

Related Questions