1

profileController.php

---when the user upload new image i want to delete the previous image in folder ... i use Laravel.....

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    public function index($slug){
        
        return view('profile.index')->with('data', Auth::user()->profile);
    }


    public function uploadPhoto(Request $request) {

$file = $request->file('pic');
$filename = $file->getClientOriginalName();
$path = 'storage/img';

$file->move($path, $filename);
$user_id = Auth::user()->id;

DB::table('users')->where('id',$user_id)->update(['pic' =>$filename]);

return redirect('/editProfile')->withSuccess('Your image was successful.');

}

2 Answers 2

1

You need to get current image path of user before updating it with new one. So that you can use that old path to delete image file.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    public function index($slug){

        return view('profile.index')->with('data', Auth::user()->profile);
    }


    public function uploadPhoto(Request $request) {

// Uplaod new image
$file = $request->file('pic');
$filename = $file->getClientOriginalName();
$path = 'storage/img';
$file->move($path, $filename);
$user_id = Auth::user()->id;


// Get current image of user, then delete it
$user = User::find(Auth::user()->id);
File::delete($user->pic);


// Then update profile picture column in database
DB::table('users')->where('id',$user_id)->update(['pic' =>$filename]);

return redirect('/editProfile')->withSuccess('Your image was successful.');

}
Sign up to request clarification or add additional context in comments.

Comments

0

Before update you can access to old pic with

Auth::user()->pic

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.