Ad
Laravel 5.6: Many-to-many Relationship Returns Empty Object
I'm setting up a many-to-many relationship in Laravel 5.6 models but, since I'm not following Laravel's naming convention, I'm surely making a mistake on table/foreign keys name that makes it not working.
My tables related to the blog section all have a blog_
prefix:
blog_posts
collects all posts info (id
,title
,article
, etc.)blog_tags
defines the tags that can be used to tag the post (id
,name
)blog_posts_tags
is the pivot table that creates the relationships between posts and tags (id
,post_id
,tag_id
)
As said, I'm trying to set up the relationships in Laravel:
Model: BlogPost.php
/**
* The tags that belong to the post.
*/
public function tags()
{
return $this->belongsToMany('App\BlogTag', 'blog_posts_tags', 'post_id', 'tag_id');
}
Model: BlogTag.php
/**
* The posts that belong to the tag.
*/
public function posts()
{
return $this->belongsToMany('App\BlogPost', 'blog_posts_tags', 'tag_id', 'post_id');
}
The problem is that, when I call tags()
method, the returned object hasn't the tags inside:
$post = BlogPost::find($id);
$tags = $post->tags();
Where am I wrong?
Ad
Answer
$post->tags()
returns you releated instance with query builder.
if you want to get releated tag values, just use name of relation
example: $tags = $post->tags;
foreach($tags as $tag){
var_dump($tag);
}
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad