php - 拉维尔 5.5 |标签只出现在最后一篇文章中?

标签 php laravel laravel-5

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

这是我的代码;

博客 Controller ;

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');
    }

我哪里弄错了?

最佳答案

后模型

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

标签模型

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

你的 Blade 弄错了。

<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>

关于php - 拉维尔 5.5 |标签只出现在最后一篇文章中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094877/

相关文章:

php - 一种更有效的为枢轴构建数据库的方法

mysql - 我有两个名为 created_at 和 updated_at(timestamps) 的字段,我想在我的 where 子句中的这些日期之间进行搜索

php - ICS 文件格式是否允许更新和删除事件?

php - Yii CSRF 禁用操作

php - 我如何连接到 laravel 中的多个数据库以进行相同的查询?

javascript - 拉维尔 : Different json output for the same query

laravel - 在 Laravel 5.4 中更改 FROM 和 REPLYTO 地址

php - PHP 中的 bool 赋值运算符

php - 从日期中减去 8 天 + 秒

javascript - laravel 中的搜索功能无法正常工作