Laravel 5.5 |标签只出现在最后一篇帖子中?

时间:2017-11-03 11:37:20

标签: php laravel laravel-5

我想显示帖子的标签,但是当我尝试显示时,标签只出现在最后一篇文章中。

这是我的代码;

BlogController;

public function getSingle($slug){
    $posts = Post::where('slug', $slug)->first();

    return view('front.pages.single')->with('post', $posts);
}

Single.blade.php

 <div class="blog-main">
    {!! $post->body !!}
    <hr>
        @if($post->tags()->count() == 0)

        {{"Add Some Tags"}}

        @elseif($post->tags()->count() > 0)

         <p> <strong>Tags:</strong>
        @foreach($post->tags as $tag)

        <span class="btn btn-outline-primary btn-sm" ><a  href="{{route('tags.show',$tag->id)}}" >{{$tag->name}} </a></span>

         @endforeach </p>
         @endif
 </div>

与标签和帖子的关系

发布模型

 public function tags(){
        return $this->belongsToMany('App\Tag');
}

标记模型

public function posts(){
        return $this->belongsToMany('App\Post');
    }

我在哪里弄错了?

1 个答案:

答案 0 :(得分:1)

发布模型

public function tags(){
    return $this->hasMany('App\Tag', 'foreign_id');
}

标记模型

public function post(){
    return $this->belongsTo('App\Post', 'foreign_id);
}

你的刀片错了。

<div class="blog-main">
{!! $post->body !!}
<hr>
    @if($post->tags->count() == 0)

    {{"Add Some Tags"}}

    @elseif($post->tags->count() > 0)

     <p> <strong>Tags:</strong>
    @foreach($post->tags as $tag)

    <span class="btn btn-outline-primary btn-sm" ><a  href="{{route('tags.show',$tag->id)}}" >{{$tag->name}} </a></span>

     @endforeach </p>
     @endif
 </div>