msslgomez
2 months ago
491
8
Laravel

Check if file exists in public folder

Posted 2 months ago by msslgomez

I'm creating an excel and I want to make sure it got created to return a download of said file, and after the zip is created I want to delete all the files that went into it to clean out excess files as they aren't needed after the zip is created.

This is my funcion where I'm creating the zip, this works, but all the files stay there and just wasting space.

public function getZip(Request $request)
    {
        $job_request = JobRequest::findOrFail($request->request_id);
        if ($job_request->user_id == auth()->user()->id) {
            $zip = new ZipArchive;

            if (true === ($zip->open('ReportesTodos-' . $request->request_id . '.zip',
                    ZipArchive::CREATE | ZipArchive::OVERWRITE))) {

                foreach ($job_request->reports as $report) {
                    if (Storage::disk('report_upload')->exists($report->report_name . '.xlsx')) {
                        $zip->addFile(public_path('reports\' . $report->report_name . '.xlsx'),
                            $report->report_name . '.xlsx');
                    }
                }
                $zip->close();
            }

           
        }
        return response()->download(public_path('ReportesTodos-' . $request->request_id . '.zip'),
            'ReportesTodos-' . $request->request_id . '.zip');
    }

The zip gets created in the public folder at this path public\ReportesTodos-5.zip so what I think is the best solution is to check if it exists and when that is true delete all the files that are inside the zip that are at public/reports/ and after that return the download.

How can I do that?

Please sign in or create an account to participate in this conversation.