i have problem in laravel eloquent relationships. there is 2 model in my application: article and category.
article model:
public function category()
{
return $this->belongsToMany('App\Category');
}
category model:
public function article()
{
return $this->hasMany('App\Article');
}
the relation between this tow is hasMany (Category -> article)
& belongsToMany (Article -> category)
.
category will fetch by requested slug using this method at categoryController:
$category = Category::where('slug', '=', $slug)->get();
problem will be shown in view when i want to fetch articles from category and nothhing will return back:
@foreach ($category->article->all() as $article)
{{ $article->name }}
@endforeach
and from @dd($category->article)
we will get empty collection:
Collection {#323 ▼
#items: []
}
As @lagbox tried to highlight in a comment, for pivot tables, both relationships should be belongsToMany
. Inverse of hasMany
is belongsTo
.
If one article belongs to many categories, and one category can have many articles, then, ideally, there it should be a many-to-many
relationship. Category model should have a belongsToMany
relationship with Article model and vice versa. Additionally, there should be a pivot table, article_category
. And as many have suggested, you can get articles the belongs to a category by using @foreach($category->articles as $articles)
You can read more about many to many here: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many
You can use @forelse blade directive like
@forelse ($category->article as $article)
<li>{{ $article->name }}</li>
@empty
<p>No articles</p>
@endforelse
You can check that here
You dont need to write $category->article->all()
. $category->article
itself will return all articles. So just use like,
@foreach ($category->article->all() as $article)
{{ $article->name }}
@endforeach
For eager loading articles, you can use with
keyword
$category = Category::with('article')->where('slug', '=', $slug)->get();
In your controller
$category = Category::with('article')->where('slug',$slug)->get();
In your blade.php file
@foreach($category->article as $article)
<li>{{ $article->name }}</li>
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.