在Laravel中获取与类别相关的帖子,并在每个类别的侧边栏中显示它

时间:2020-03-04 10:44:03

标签: php laravel laravel-6

我的类别是视频,新闻,音乐,评论,我想在单独的侧边栏中显示与每个类别相关的帖子。

即,视频边栏将具有与之关联的所有帖子,音乐边栏将具有与之关联的所有帖子显示在侧边栏上。

**Posts**
id | title | text

**Categories_Posts**
category_id | post_id

**Category**
id | name

模型

class Post extends Model
    {    
            public function categories()
            {
                return $this->belongsToMany(Category::class, 'categories_posts');
            }
    }

class Category extends Model
   {
           public function posts()
           {
              return $this->belongsToMany(Post::class, 'categories_posts');
           }
   }

控制器

class MainController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $posts= Post::latest()->paginate(15);
        $posts = Post::with('categories')->get();
        return view('pages.welcome',compact('posts'));
    }

我在我看来是这样做的,但是它在侧边栏上显示了所有帖子和类别名称,但是我要真正将它们分开,即新闻帖子应该在新闻侧边栏上显示

@foreach($posts as $post)
<div> {{ $post->subject }} </div>
<div> {{ $post->image }} </div>
 @foreach($post->categories as $category)
  <div> {{ $category->name}} </div>
  @endforeach
 @endforeach

请帮助

0 个答案:

没有答案