Support the ongoing development of Laravel.io →
Eloquent Views Blade

I have an Image model, which I want to override the delete method to erase the file from the system when deleting on the database, as follows:

class Image extends Eloquent{

	public function delete()
	{
		// code to delete the media from the file system before deleting
		parent::delete();
	}

}

Now I have another model which has a reference to image:

class Board extends Eloquent{

    public function cover(){
        return $this->belongsTo('Image');
    }
}

Now, when I run the command:

$media = $board->cover;
$media->delete();

It deletes the board, and not the image!

Any ideas on what could be wrong?

Last updated 3 years ago.
0

Instead of overwriting delete() method, you could use model event as described here: http://laravel.com/docs/4.2/eloquent#model-events

Image::deleted(function ($image)
{
    // delete media
});

Notice I used deleted event and not deleting. I believe it's safer to delete record first and then the media.

Last updated 3 years ago.
0

Also, I don't think that technically you aren't actually get the file in question, perhaps just the path to it.

You might need to do something like:

File::delete($media);

Although it is a little difficult to say without seeing the rest of your code.

Last updated 3 years ago.
0

The file deletion part works fine T2, the problem is that the parent object (in this case $board) gets deleted along with the $media object..

Which, I found out.. my ON DELETE was set to CASCADE on the database. I feel stupid ... haha

Anyways.. let it be archived in case someone else faces the same problem.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

raphadko raphadko Joined 13 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.