update file name of a file and updating data in database at the same time in laravel

I have a working upload file function. here's the code

public function store(Request $request)
{  
    $request->validate([
        'name' => 'required',
        'filename' => 'required|mimes:jpeg,png,jpg,gif,svg,doc,docx,xls,xlsx,pdf,txt|max:2048',
    ]);

    $fileName = auth::user()->id.'_'.$name.'.'.request()->filename->getClientOriginalExtension();

    request()->filename->storeAs('files', $fileName);

    File::create ([
        'name'      => $name,
        'filename'  => $fileName,
        'user_id'   => $request['user_id'],
        'extension' => request()->filename->getClientOriginalExtension(),
    ]);

    return redirect('dashboard/files')->with('flash_message', 'File added!');
}

now my problem is how am I going to update the filename of the file once I update the name in the database?

thanks in advance!

1 answer

  • answered 2019-09-15 23:15 Teoman Tıngır

    Well you may want to look at observers. That would be good practise.. Observers fires when CRUD operations done. So when you change a file name on database, you'll be there through observers.

    first create an observer.

    php artisan make:observer FileObserver --model=File
    

    then register your observer on AppServiceProvider::boot.

    public function boot()
    {
        File::observe(FileObserver::class);
    }
    

    Open your FileObserver and edit "updated" method. Below method will run when a file record updated through File model.

    public function updated(File $file)
    {
        // get old file name
        $dirty = $file->getDirty();
        $oldFileName = $dirty["filename"] . "." . $file->extension;
        // get new file name
        $newFileName = $file->filename . "." . $file->extension;
        // replace old file name with new
        Storage::move('files/' . $oldFileName, 'files/' . $newFileName);
    }