【问题标题】:Redirect if there are no posts in the category Laravel如果 Laravel 类别中没有帖子,则重定向
【发布时间】:2021-04-27 13:29:11
【问题描述】:

如果用户选择了没有帖子的类别,我想将他们重定向回来。我已经尝试过这样的事情,但它不起作用:

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

类别型号:

class Category extends Model
{
    use HasFactory;

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

    public function posts(){
      return $this->hasMany(Post::class);
    }
}

【问题讨论】:

  • 您能否提及您的类别模型?它有助于更​​好地理解
  • 好的,更新了帖子。
  • 第一种方法是正确的,但你总是得到$check = Category::withCount('posts')-&gt;first();,而不是对应于所走路线的类别
  • 又该如何正确操作呢?

标签: php laravel redirect


【解决方案1】:
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。

【讨论】:

  • 谢谢! has 函数正是我所需要的。
猜你喜欢
  • 2021-01-05
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2019-01-17
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
相关资源
最近更新 更多