I am trying to delete data by using a foreign key but unfortunately not deleting from FreeDownloadFiles tables how can I delete data from this table please help me thanks.
Note: data is successfully deleting from freedownload table but not deleting from FreeDownloadFiles tables
free_download table
id | name | images
free_download_files table
id | free_download_id | images
Controller
public function destroy(Request $request)
{
$freedownload = FreeDownload::findOrFail($request->deleteId);
$freedownloadfiles = FreeDownloadFiles::where('free_download_id', $request->deleteId)->get();
foreach ($freedownloadfiles as $key => $value) {
$delete = $value->delete();
}
// apply your conditional check here
if (false) {
$response['error'] = 'This FreeDownload has something assigned to it.';
return response()->json($response, 409);
} else {
Storage::disk('yourstitchart')->delete($freedownload->icon);
$response = $freedownload->delete();
return response()->json($response, 200);
}
}
You can automate the deleting of the images/files associated with the FreeDownloadFiles
records by hooking into the model deleting
event in the FreeDownloadFiles
model definition.
class FreeDownloadFile extends Model
{
protected static function booted()
{
static::deleting(function ($record) {
/**
* if images field contains string with comma separated paths to image files
* convert to array explode(',', $record->images)
* replace comma with whatever separator is used eg ;
*/
foreach(explode(',', $record->images) as $image) {
Storage::delete($image);
}
});
}
}
Similarly to automate deleting of FreeDownloadFiles
associated with a FreeDownload
we can hook into the deleting
event for FreeDownload
class FreeDownload extends Model
{
protected static function booted()
{
static::deleting(function ($record) {
//can also use higher order magic
//$record->freeDownloadFiles->each->delete();
foreach($record->freeDownloadFiles as $file) {
$file->delete();
}
});
}
}
Then the controller method can become simple as
public function destroy(Request $request)
{
$freedownload = FreeDownload::findOrFail($request->deleteId);
// apply your conditional check here
if (false) {
$response['error'] = 'This FreeDownload has something assigned to it.';
return response()->json($response, 409);
} else {
Storage::disk('yourstitchart')->delete($freedownload->icon);
$response = $freedownload->delete();
return response()->json($response, 200);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments