You don't need to check for the single category and article relation.
I'd suggest you read the documentation on Laravel.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
Hello all! 0
I have Articles table and it haves category_id witch is related to AllCategories table. But now i added + articles_categories pivot table. Now i', adding one category with category_id and multi categories with pivot table.
public function category($slug, $page = 1)
{
$offsetPage = ($page - 1);
$perPage = 24;
$category = AllCategory::bySlug($slug);
if (!$category) {
abort(404);
}
$pivot = $category->manyArticles()->get();
$categoryArticles = $category->articles()->skip($perPage * $offsetPage)->take($perPage)->get();
$lastPage = ceil($category->articles()->count() / $perPage);
return view('pages/category')
->with('category', $category)
->with('perPage', $perPage)
->with('page', $page)
->with('lastPage', $lastPage)
->with('categoryArticles', $categoryArticles)
->with('pivot', $pivot);
}
In $categoryArticles i'm getting articles with category_id. I cant get pivot categories with
$category->manyArticles()->get();
But what to do with pagination then? i need single category articles and multi category articles in single variable.
blade
@foreach($categoryArticles as $article)
@if(!empty($article->getUrl()))
<a class="w-100" href="{{$article->getUrl()}}">
@if(!empty($article->title))
<div class="w-100 font-size-14 font-size-md-12 font-size-xs-12 font-medium-caps text-blue-100 pt-15px pt-xs-5px crop-2 crop-xs-4 pr-35px pr-xs-15px h-55px h-md-50px h-xs-75px">{{$article->tr('title')}}</div>
@endif
</a>
@endif
<div class="d-flex pt-20px pt-xs-5px justify-content-between">
<div class="d-flex align-items-center">
<span class="fas fa-calendar text-light-black font-size-14 font-size-sm-13 pr-5px"></span>
@if(!empty($article->published_at))
<div class="font-base font-size-13 font-size-sm-12 mt-2px mt-sm-2px text-light-black">{{Carbon\Carbon::parse($article->published_at)->format('d/m/Y')}}
</div>
@endif
</div>
</div>
@endforeach
What to do : /
@furqanDev I found the way!
$offsetPage = ($page - 1);
$perPage = 24;
$category = AllCategory::bySlug($slug);
if (!$category) {
abort(404);
}
$ids_from_main_category = $category->articles()->pluck('id')->toArray();
$ids_from_pivot = $category->manyArticles()->pluck('articles.id')->toArray();
$both_ids = array_merge($ids_from_pivot, $ids_from_main_category);
$articles = Article::whereIn('id', $both_ids)->publishedOrder()->statusOn();
$categoryArticles = $articles->skip($perPage * $offsetPage)->take($perPage)->get();
$lastPage = ceil($category->articles()->count() / $perPage);
This code is doing does exactly what I wanted. : )
Please or to participate in this conversation.