RoughLik's avatar

Update images from database and directory

Hi, I created this feature to save multiple images. Everything is fine so far, but I wish I could update them without deleting and adding again Could I proceed with a find id depending on the model used and upload them again? Or how can you delete the old ones and add the new ones instead?

if($request->hasfile('images'))
        {
           $imageSize = 0;

           foreach($request->file('images') as $image)
           {
                $name = $image->getClientOriginalName();
                $image->move(public_path().'/files/' . $dataPage->id . '/', $name);  

                Files::create([
                    'file_name' => $name,
                    'app_type'  => 'App\Pages',
                    'model_id'  => $dataPage->id,
                    'path'      => '/files/' . $dataPage->id . '/', $name
               ]);
           }
        }

Should I make a function an update a find by id and try to delete what is old and add again? Or how could I proceed with what I have? the model is Pages

0 likes
1 reply
davy_yg's avatar

For update you have to use find($id) and the delete the old one before updating it to a new one.

Here I give you an example of an update functions for reference (this is a function to update banner slides in a company profil website):

HomeSlidesController.php

	 public function update(Request $request, $id)
	{
    //
    $id = $request->id;
    $slides = HomeSlides::find($id);

    if($slides->image){

        $this->validate($request, [
            'title' => 'required'
        ]);

    }else{

        $this->validate($request, [
            'title' => 'required',
            'slides' => 'required|image|mimes:jpg,jpeg,png|max:10000|dimensions:min_width=1950,min_height=550,max_width=2050,max_height=650'
        ]);

    }
    
    $file = $request->file('slides');
        
    if($file)
    {
        
        //storage/app
        Storage::delete($slides->image);
        
        //storage/app/slides/random.jpeg
        $path = $request->file('slides')->store('public/slides');
        
        Log::info('path :'.$path);

        $slides->image = $path;

    }

    $slides->title = $request->title;

    $slides->update();

    Session::flash('flash', 'Successfully save data');
       
    $slides = HomeSlides::find($id);

    return view('admin.home.edit_home_slides')->with('list', $slides);
	}

Please or to participate in this conversation.