Yohei Umezu
Yohei Umezu

Reputation: 431

laravel 5.8 eloquent: has many relations model

I am creating event information system and want to show tags in posts/show.blade.php.

But I got an error.

Property [name] does not exist on this collection instance

In posts table, I have category_id. And I created post_tag table.

Do I need to create another new table ?

How to show tags in show.blade.php ?

Please give me a hand.

post.php

   public function tags() 
{
    return $this->belongsToMany(Tag::class);

}
public function hasTag($tagId)
    {
        return in_array($tagId, $this->tags->pluck('id')->toArray());
    }

tag.php

public function posts()
{
    return $this->belongsToMany(Post::class);
}

category.php

public function posts()
{
    return $this->hasMany(Post::class);
}

create_posts_table

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image');
        $table->unsignedBigInteger('category_id');
        $table->string('organizer');
        $table->string('title');
        $table->string('place');
        $table->string('map');
        $table->date('date');
        $table->timestamp('published_at')->nullable();
        $table->text('description');
        $table->timestamps();
    });

create_categories table

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

create_tags table

Schema::create('tags', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

post_tag table

Schema::create('post_tag', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('post_id');
        $table->integer('tag_id');
        $table->timestamps();
    });

ResultsControllere.php

public function show($id,Post $post)
{
    $post= Post::find($id);
    $post->category;
    $post ->tags;
    return view('posts.show',compact('post'));
}

show.blade.php

Tags:
  <div class="tags">
     {{ $post->tags->name }}
 </div>

Upvotes: 0

Views: 103

Answers (2)

Salman Zafar
Salman Zafar

Reputation: 4035

According to your defined relationship post has many tags so you cannot access the one to many relationship directly you may have to loop through to get the tag detail e.g name

<div class="tags">
     @foreach($post->tags as $tag)
     {{ $tag->name }}
     @endforeach
</div>

Thanks.

Upvotes: 2

Aakash Tushar
Aakash Tushar

Reputation: 504

$post->tags should return a collection so there is no property name.

Your show.blade.php code should be:

<div class="tags">
    @foreach($post->tags as $tag)
        {{ $tag->name }}
    @endforech
</div>

Upvotes: 2

Related Questions