简体   繁体   English

如果 Laravel 类别中没有帖子,请重定向

[英]Redirect if there are no posts in the category Laravel

I want to redirect users back if they have selected a category that has no posts.如果他们选择了没有帖子的类别,我想将用户重定向回来。 I've tried something like this, but it doesn't work:我已经尝试过这样的事情,但它不起作用:

$check = Category::withCount('posts')->first();
if($cheсk->posts_count < 1){
    return redirect()->back()->with('warning', 'No posts in this category!');
  }

Or:或者:

if(Category::withCount('posts') < 1){
    return redirect()->back()->with('warning', 'No posts in this category!');
  }

Category model:类别 model:

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'user_id',
        'code',
        'img'
    ];

    public function posts(){
      return $this->hasMany(Post::class);
    }
}
You can use following code:
$isCategoryHasPosts = Category::where('id','<specify_category_id>')->has('posts')->count();
if(!$isCategoryHasPosts) {
    return redirect()->back()->with('warning', 'No posts in this category!');
}

Note: replace specify_category_id with your actual category Id.注意:将指定类别 ID 替换为您的实际类别 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM