Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1971
半阙折子戏
半阙折子戏 2020-11-22 17:03

When I delete a row using this syntax:

$user->delete();

Is there a way to attach a callback of sorts, so that it would e.g. do this auto

13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 17:38

    I would iterate through the collection detaching everything before deleting the object itself.

    here's an example:

    try {
            $user = User::findOrFail($id);
            if ($user->has('photos')) {
                foreach ($user->photos as $photo) {
    
                    $user->photos()->detach($photo);
                }
            }
            $user->delete();
            return 'User deleted';
        } catch (Exception $e) {
            dd($e);
        }
    

    I know it is not automatic but it is very simple.

    Another simple approach would be to provide the model with a method. Like this:

    public function detach(){
           try {
                
                if ($this->has('photos')) {
                    foreach ($this->photos as $photo) {
        
                        $this->photos()->detach($photo);
                    }
                }
               
            } catch (Exception $e) {
                dd($e);
            }
    }
    

    Then you can simply call this where you need:

    $user->detach();
    $user->delete();
    

提交回复
热议问题