如果子表>0,则Laravel防止删除

rjzwgtxy  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(118)

我使用Laravel 5.8,我有这种情况。我想防止删除一个类别,如果它有产品在它。这是我到目前为止
Category.php

public function products(){
    return $this->hasMany('App\Product');
  }

  protected static function boot() {
    parent::boot();

    static::deleting(function($category) {
         if ($category->products()->count() > 0) {
            return false;
        }
    });

  }

CategoriesController.php

public function destroy($id) {
      $category = Category::findOrFail($id);
      $delete_status = $category->delete();

      if($delete_status == 1) {
        return redirect()->route('categories.index')->with('success','Deleted Sucesfully');
      } else {
        return redirect()->route('categories.index')->with('error','Cant delete bacause it has products in it');
      }
    }

到目前为止还能用,但我觉得有点粗糙。$delete_status变量返回1,如果类别中没有任何产品,但如果类别中有产品,则不返回任何值,这也是我使用if/else而不是if/elseif的原因。
有没有更好的方法?

guykilcj

guykilcj1#

类别.php

public function products(){
    return $this->hasMany('App\Product');
}

类别控制器.php

public function destroy($id)
{
    $category = Category::find($id);
    if (empty($category))
        abort(404);
    if($category->products->count())
        redirect()->route('categories.index')->with('error',"Can't delete because it has products in it");

    try {
        $category->delete();
        redirect()->route('categories.index')->with('success', 'Category has been deleted successfully');
    } catch (\Exception $e) {
        redirect()->route('categories.index')->with('error','Something went wrong please try again later!');
    }
}
axkjgtzd

axkjgtzd2#

因为你只使用了一个return。这意味着当进入if函数时,在删除函数中,返回一个东西,否则什么都不返回。也许你必须用else语句返回任何东西。

相关问题