[英]Redirect if there are no posts in the category Laravel
如果他们选择了没有帖子的类别,我想将用户重定向回来。 我已经尝试过这样的事情,但它不起作用:
$check = Category::withCount('posts')->first();
if($cheсk->posts_count < 1){
return redirect()->back()->with('warning', 'No posts in this category!');
}
或者:
if(Category::withCount('posts') < 1){
return redirect()->back()->with('warning', 'No posts in this category!');
}
类别 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!');
}
注意:将指定类别 ID 替换为您的实际类别 ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.