Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将具有特定类别的帖子发送到Laravel中的视图_Php_Mysql_Laravel - Fatal编程技术网

Php 将具有特定类别的帖子发送到Laravel中的视图

Php 将具有特定类别的帖子发送到Laravel中的视图,php,mysql,laravel,Php,Mysql,Laravel,我正在用Laravel框架写博客。我想向前端视图发送具有特定类别的帖子。当我有一个单独的类别表连接到posts表时,我该怎么做? 例如,“我的帖子”表有一个连接到该类别表的类别id 后模型: public function category(){ return $this->belongsTo('App\Category'); } 类别模型: public function posts(){ return $this->hasMany('App\Post');

我正在用Laravel框架写博客。我想向前端视图发送具有特定类别的帖子。当我有一个单独的类别表连接到posts表时,我该怎么做? 例如,“我的帖子”表有一个连接到该类别表的类别id

后模型:

public function category(){

    return $this->belongsTo('App\Category');
}
类别模型:

public function posts(){

    return $this->hasMany('App\Post');
}
现在,我如何才能将帖子发送到视图,但只能发送具有特定类别的帖子,例如“归档”

我知道应该是这样的:

public function index()
{

    $rows = Post::notdeleted()->get();

    return view('admin.posts.index', compact('rows'));
}

但我不知道如何获取该类别,因为它是posts表中的category\u id 1和category表中的“archive”。

您可以这样做:

public function index()
    {
        $rows = Post::whereHas('category',function($q){
            $q->where('category_name','archive');
        })->get();
        return view('admin.posts.index', compact('rows'));
    }

我想你应该按类别名称筛选帖子

public function index(){
  // For example Archive
  $categoryName= request()->get('category_name');
  $posts = Post::whereHas('category',function($query) use ($categoryName){
     $query->where('name','like',"%{$categoryName}%");
  }); 
  return view('admin.posts.index', compact('posts'));
}