Home > OS >  Laravel Storage doesn't delete file data
Laravel Storage doesn't delete file data

Time:12-23

Hi i want to make function inside function delete file(in Controller), the reason i made function is not repeating same codes in every if condition. but there is problem when i try to input variable in processDelete's parameter on first condition like this

public function delete_file($file, $track)
    {   
        function processDelete($strfile, $file, $fileInput){
            //delete
            $dell = Task::where($strfile, 'post-files/'. $file)->first();
        
            Storage::delete($fileInput);
            //delete data
            $dell->update([$strfile => null]);
        }
        
            if($track == 1)
            {
                processDelete('file_jamlak', $file, '$dell->file_jamlak');
            }
            else if($track == 2)
            {
                $dell = Task::where('file_kontrak', 'post-files/'. $file)->first();
                Storage::delete($dell->file_kontrak);
                //delete data
                $dell->update(['file_kontrak' => null]);
            }
            else if($track == 3)
            {
                $dell = Task::where('file_jamuk', 'post-files/'. $file)->first();
                Storage::delete($dell->file_jamuk);
                //delete data
                $dell->update(['file_jamuk' => null]);
            }
            else if($track == 4)
            {
                $dell = Task::where('file_sprin_pc', 'post-files/'. $file)->first();
                Storage::delete($dell->file_sprin_pc);
                //delete data
                $dell->update(['file_sprin_pc' => null]);
            }

the third parameter is supposed tell Storage to delete '$dell->file_jamlak', but my file data still remains in folder. Please anyone can help my code?

CodePudding user response:

It doesn't work like that, even if it works, it's plain ugly. Extract the function to new function and call it...

private function processDelete($strfile, $file)
{
    $dell = Task::where($strfile, 'post-files/' . $file)->first();

    Storage::delete($dell->$strfile);

    $dell->update([$strfile => null]);
}


public function delete_file($file, $track)
{
    match ($track) {
        1 => $this->processDelete('file_jamlak', $file),
        2 => $this->processDelete('file_kontrak', $file),
        3 => $this->processDelete('file_jamuk', $file),
        4 => $this->processDelete('file_sprin_pc', $file),
        default => null
    };
}

If you call delete_file for one file mostly, you can set it default.

  • Related