I am using laravel 6
I have 2 tables:
Table 1: id, description.
Table 2: id, table1_id, file, file2
table1 has the relationship of hasMany
table2 has a belongsTo relationship
Deleting table1 also deletes table2 . What I want to do is that when deleting table1, table2 is deleted along with all the files that I have in the project whose path is in the database in the file fields
If I separately delete a field from table2, it is deleted along with the file with the following code:
unlink(storage_path('app/public/'.$tabla2->file));
unlink(storage_path('app/public/'.$tabla2->file2));
But trying to delete everything from table1 doesn't work for me, I've tried this:
public function destroy($id){
$tabla1 = Tabla1::find($id);
$tabla2 = Tabla2::all()->where('tabla1_id', $id);
if(isset($tabla2->file)){
unlink(storage_path('app/public/'.$tabla2->file));
}
if(isset($tabla2->file2)){
unlink(storage_path('app/public/'.$tabla->file2));
}
$tabla1->delete();
}
On the one hand, you can do the query like this, instead of fetching all the rows and then filtering the collection:
Then, to delete the files, I'd suggest using File Storage .
You can declare an array to save the names of the files that exist on the disk. Using
Storage::disk('public')
it you will no longer have to specify the path withstorage_path('app/public/'. ...)
, since it is the default path of that diskStorage
:Once you have the array with all the existing filenames, you can pass it directly to the
delete()
de methodStorage
:To delete records you can use
And to make a truncate