I'm trying to delete single user comments and the pictures related with them, by deleting them from both the database records and storage. Unfortunately I keep getting errors. Below is the code I have so far.
Tables: Comments: id, comment, user_id, person_id pictures: id, image, comment_id, user_id, person_id
Relationships: Comment:
public function pictures()
{
return $this->hasMany('App\Picture', 'comments_id', 'id');
}
pictures:
public function comments()
{
return $this->belongsTo('App\Comment', 'comments_id');
}
Controller:
public function destroy($id)
{
$comment = Comment::find($id);
Storage::delete($comment->pictures());
$comment->delete();
Session::flash('success', 'Your comment and pictures were deleted');
return redirect()->route('home');
}
Any ideas?
You need to use pluck()
to load images file names:
$files = $comment->pictures()->pluck('filename');
Then delete these files:
foreach ($files as $file) {
Storage::delete(storage_path('images/' . $file));
}
This is just an example, you need to put correct column name instead of filename
and build the correct path to the images.
To delete images from DB:
$comment->images()->delete();
$comment->pictures()
returns the definition of a relation, not the related pictures. if you want to delete all the pictures, you'll need to iterate through them and delete one by one:
$comment = Comment::find($id);
foreach ($comment->pictures as $picture) {
// delete picture from storage
Storage::delete($picture->id); //or whatever field is used as key in the storage
// delete picture from the database - might be optional if you've set a cascade on delete behaviour in your foreign key definition
$picture->delete();
}
You need to provide filename
of image to delete image from storage
.
$comment = Comment::find($id);
foreach($comment->pictures as $picture)
Storage::delete($picture->image);
Picture::where('comment_id',$comment->id)->delete();
$comment->delete();