Reputation: 45
I have articles witch can have one single category that's Main category with category_id. and additional multi categories with pivot table everything working it's stores but i can't get data on web i'm only getting articles with single category how can i get articles with single and with multi categories in one variable?
article model:
public function category()
{
return $this->belongsTo(AllCategory::class, 'category_id', 'id');
}
public function manyCategories()
{
return $this->belongsToMany(AllCategory::class, 'articles_categories', 'article_id', 'category_id')
->using(ArticleCategory::class);
}
AllCategory model:
public function articles()
{
return $this->hasMany(Article::class, 'category_id', 'id')->orderBy('published_at', 'Desc');
}
public function manyArticles()
{
return $this->belongsToMany(Article::class, 'articles_categories', 'category_id', 'article_id')
->using(ArticleCategory::class);
}
and pivot table:
class ArticleCategory extends Pivot
{
use HasFactory;
public $table = 'articles_categories';
protected $fillable = [
'article_id', 'category_id'
];
protected $guarded = ['*'];
}
and in controller i'm getting like this
$offsetPage = ($page - 1);
$perPage = 24;
$category = AllCategory::bySlug($slug);
if (! $category) {
abort(404);
}
$categoryArticles = $category->articles()
->with('manyCategories')
->skip($perPage * $offsetPage)
->take($perPage)
->get();
I'm getting single category articles with articles() and i'm trying to get manycategories to ->with but it's only getting me single category articles what i'm doing wrong?
Upvotes: 1
Views: 64
Reputation: 50481
You could create an accessor that would add the main category to the Collection of categories that the Article belongs to.
public function getCategoriesAttribute()
{
// adding the main category (if there is one) to the Collection
return (clone $this->manyCategories)->when(
this->category,
fn ($collection, $category) => $collection->prepend($category)
);
}
Controller:
$categoryArticles = $category->articles()
->with(['category', 'manyCategories'])
->skip($perPage * $offsetPage)
->take($perPage)
->get();
View:
@foreach ($articles as $article)
@foreach ($article->categories as $category)
...
@endforeach
@endforeach
Laravel 8.x Docs - Eloquent - Mutators & Casting - Defining an Accessor
Laravel 8.x Docs - Collections - Available Methods - when
Laravel 8.x Docs - Collections - Available Methods - prepend
Upvotes: 1