Redirect, если количество постов в категории меньше 1

Я хочу редиректить пользователя назад, если он нажмет на категорию, в которой нет постов. Я пытался делать так, но что то не выходит:

$check = Post::all();
      if($check->count() < 1){
        return redirect()->back()->with('warning', 'No posts in this category!');
      }
$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!');
  }

Category model:

class Category extends Model
{
    use HasFactory;

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

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

Кто-нибудь знает как это сделать правильно?


Ответы (1 шт):

Автор решения: Hi_TecH

Помог найти верное решение один пользователь из англоязычного StackOverflow. Здесь здесь вы можете найти ответ. А я приведу его применение в моем коде:

Route::get('/posts/{category}', [MainController::class, 'category_'])->name('category');
public function category_($category){

      $categoryName = Category::where('code', $category)->first();

      if(Category::where('code', $category)->has('posts')->count() < 1){
        return redirect()->back()->with('no-posts', $categoryName->name);
      }else{
        $category = Category::where('code', $category)->get();

        return view('category_', compact('category'));
      }
    }

Модель:

  public function posts(){
      return $this->hasMany(Post::class);
    }
→ Ссылка