2

I'm setting up a CRUD, similar to an ecommerce I uploaded the image, it is stored in the public folder. The name of the image is replaced by the value of an input that the user places. This same value is saved in the database with the image extension. I was also able to delete the image, but I don't know how to update it. Can someone please give me a light?

project controller:

public function store(Request $request)
{
    $nameFile = $request->input('imageName', '');
    if($request->file('imageFile')->isValid()){
        $nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
        $request->file('imageFile')->storeAs('projects', $nameFile);
    }


    $project = new Project();

    $project->name = $request->input('name');
    $project->price = $request->input('price');
    $project->imageName = $nameFile;

    $project->save(); 

    return redirect()->route('ProjectControllerCreate');
}



public function destroy($id)
{   
    $project = Project::find($id);

    // Image
    $filePathName = public_path().'/storage/projects/'. $project->imageName;
    if( file_exists($filePathName) ){
        unlink($filePathName);
    }

    // Data
    if(!$project)
        return redirect()->back();
        
    $project->delete();

    return redirect()->route('ProjectControllerCreate');
}

public function update(Request $request, $id)
{   
    $project = Project::find($id);
    if(!$project)
        return redirect()->back();

    $project->update($request->all());

    return redirect()->route('ProjectControllerCreate');
}
GOBSRUIIZ
  • 21
  • 2

1 Answers1

1

This is how you can update :

use Illuminate\Support\Facades\Storage;

public function update(Request $request, $id)
{   
    $project = Project::find($id);
    if(!$project)
        return redirect()->back();
    // Update new image
    if($request->file('imageFile')->isValid()){
        // Delete old image
        $old_image = $project->imageName;
        Storage::delete($old_image);

        $nameFile = $request->input('imageName', '');
        $nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
        $request->file('imageFile')->storeAs('projects', $nameFile);
        $project->imageName = $nameFile;
    }

    $project->name = $request->input('name');
    $project->price = $request->input('price');
    $project->save(); 
    return redirect()->route('ProjectControllerCreate');
}
STA
  • 30,729
  • 8
  • 45
  • 59
  • I would have to delete the old one, and I believe that if I put it at the beginning of the code, it would work. But before I even do all of that, it's how I check if he selected another image – GOBSRUIIZ Jul 09 '20 at 09:23
  • @GOBSRUIIZ I updated, please make your that here ` Storage::delete($old_image);` is currect. if `$old_image` inside a directory then it would be `dirname/.$old_image` for delete file you can use unlink also , see here https://stackoverflow.com/q/45065039/4575350 – STA Jul 09 '20 at 09:35