Randolf
1042
4
Eloquent

Delete event not fired

Posted 2 years ago by Randolf

Hi, I want delete files in public folder, related to a user when the user it´s deleted. In database, I save the filename of the document.

User: id, name, mail, etc...

Document: id, user_id, title, filename, etc...

This is my setup:

//User Model
public function documents()
{
    return $this->hasMany('App\Document');
}

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

    static::deleting(function($user) {
        foreach ($user->documents() as $document) {
            Storage::delete($document->filename);
            $document->delete();
        }
    });
}

//User Controller
public function destroy($id)
{
    $user = User::findorFail($id);
    $user->delete();
    return redirect()->route('users.index')->with('message', 'Successfully deleted the user!');
}

and nothing works... User it´s deleted, but documents and files not.

I tried this too:

//Document Model
protected static function boot() {
    parent::boot();
    
    static::deleting(function($document) {
        Storage::delete($document->filename);
    });
}

//User Controller
public function destroy($id)
{
        $user = User::findorFail($id);
        $user->documents()->delete();
        $user->delete();
        return redirect()->route('users.index')->with('message', 'Successfully deleted the user!');
}

Here, user it´s deleted and document in database it´s deleted, but the files in public folder not... :(

Any help?? Thanks!!

PS: Sorry for my poor english...

Please sign in or create an account to participate in this conversation.