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?
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.
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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community