jeudi 26 septembre 2019

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">
     
 </div>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2lXXCyZ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire