Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LadyDeathKZN's avatar

Can't save final moved file path to database

Hi,

I am trying to save the moved file path to another function. The file gets uploaded then moved, I have it in a form which is using store. I want to be able to save the final path to my item column in store.

In short I would like to get the last moved path to my store function and save it in the item column when the form is submitted I keep getting this error with what I currently have:

Unresolvable dependency resolving [Parameter #0 [ string $path ]] in class Symfony\Component\HttpFoundation\File\UploadedFile

or variable is not defined, though I have no idea how it can't be defined if it is defined in saveFile function.

The file upload and saving

/**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        // Group files by the date (week
        $dateFolder = date("Y-m-W");
        // Build the file path
        $filePath = "upload/{$dateFolder}/";
        $finalPath = storage_path("app/".$filePath);
        // move the file name
        $file->move($finalPath, $fileName);
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }
    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        // Add timestamp hash to name of the file
        $filename .= "_" . md5(time()) . "." . $extension;
        return $filename;
    }

My store function that submits the form with the one input field

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $clientupload = new ClientUpload;
        $clientupload->form_id = $request->form_id;
        $clientupload->item = $this->saveFile($request, $finalPath);

        $form->save();

        return redirect(route('client-upload.index'))->with('success', 'Upload added successfully.');

    }

My create form if need be

<form action="{{route('client-upload.store')}}" method="POST">
                    @csrf
                        <div class="row">
                            <div class="col-md-3">
                            <label for="form_id">Job No</label>
                                <select class="form-control" name="form_id" id="form_id">
                                    @foreach($forms as $form)
                                    <option value="{{$form->job_description}}">{{$form->job_description}}</option>
                                    @endforeach                    
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 pt-3">
                              <div class="text-center" >
                                  <div id="resumable-error" style="display: none">
                                      Resumable not supported
                                  </div>
                                  <div id="resumable-drop" style="display: none">
                                      <p>
                                        <button id="resumable-browse" data-url="{{ route('cupload') }}" >Upload</button> or drop here
                                      </p>
                                  </div>
                                  <ul id="file-upload-list" class="list-unstyled"  style="display: none">

                                  </ul>
                                  <br/>
                              </div>
                            </div>
                        </div>
                        <div class="text-center pt-2">
                            <button class="btn btn-primary btn-block" type="submit">Submit</button>
                        </div>
                    </form>
0 likes
6 replies
Snapey's avatar

Why are you returning a response object from the file store. All your store method needs back is the filepath?

change this

        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);

to

    return $filePath;

you are also doing this

$form->save();

when the object you have been creating is $clientUpload

LadyDeathKZN's avatar

Thank you will try this. This is from the laravel-chunk-upload controller example. So honestly I wouldn't even know why haha.

LadyDeathKZN's avatar

@Snapey

I changed the following:

public function store(Request $request)
    {
        $clientupload = new ClientUpload;
        $clientupload->form_id = $request->form_id;
        $clientupload->item = $this->saveFile($request, $filePath);
 
        $$clientUpload->save();
 
        return redirect(route('client-upload.index'))->with('success', 'Upload added successfully.');
    }

And this:

protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        // Group files by the date (week
        $dateFolder = date("Y-m-W");
        // Build the file path
        $filePath = "upload/{$dateFolder}/";
        $finalPath = storage_path("app/".$filePath);
        // move the file name
        $file->move($finalPath, $fileName);
        return $filePath;
    }

but getting this error:

ErrorException (E_NOTICE)
Undefined variable: filePath

I don't understand how it is not getting the variable, am I missing something very small here? And thank you for spotting that $form variable!!

LadyDeathKZN's avatar

here the entire controller:

<?php

namespace App\Http\Controllers;

use App\ClientUpload;
use App\Form;
use Storage;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;

class ClientUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('uploads.client.index');
    }

    public function create(){
        $forms = Form::all();
        return view('uploads.client.create', [
            'forms'=>$forms
        ]);
    }    

    /**
     * Handles the file upload
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws UploadMissingFileException
     * @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadFailedException
     */
    public function upload(Request $request) {
        // create the file receiver
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
        // check if the upload is success, throw exception or return response you need
        if ($receiver->isUploaded() === false) {
            throw new UploadMissingFileException();
        }
        // receive the file
        $save = $receiver->receive();
        // check if the upload has finished (in chunk mode it will send smaller files)
        if ($save->isFinished()) {
            // save the file and return any response you need, current example uses `move` function. If you are
            // not using move, you need to manually delete the file by unlink($save->getFile()->getPathname())
            return $this->saveFile($save->getFile());
        }
        // we are in chunk mode, lets send the current progress
        /** @var AbstractHandler $handler */
        $handler = $save->handler();
        return response()->json([
            "done" => $handler->getPercentageDone(),
            'status' => true
        ]);

        return $filePath;
    }
    
    /**
     * Saves the file
     *
     * @param UploadedFile $file
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file)
    {
        $fileName = $this->createFilename($file);
        // Group files by the date (week
        $dateFolder = date("Y-m-W");
        // Build the file path
        $filePath = "upload/{$dateFolder}/";
        $finalPath = storage_path("app/".$filePath);
        // move the file name
        $file->move($finalPath, $fileName);
        return response()->json([
            'path' => $filePath,
            'name' => $fileName
        ]);
    }
    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        // Add timestamp hash to name of the file
        $filename .= "_" . md5(time()) . "." . $extension;
        return $filename;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $clientupload = new ClientUpload;
        $clientupload->form_id = $request->form_id;

        $clientupload->save();

        return redirect(route('client-upload.index'))->with('success', 'Upload added successfully.');

    }
}

Snapey's avatar

Not sure what of the posted code you are using. You appear to have two ways to save a file.

The return code I mentioned earlier should have been placed in the saveFile function not the upload function, but you seem to have removed the line where the method was called and the filePath stored?

LadyDeathKZN's avatar
LadyDeathKZN
OP
Best Answer
Level 1

Hi managed, to fix the issue - thank you for your efforts though

protected function saveFile(UploadedFile $file) { $fileName = $this->createFilename($file); // Build the file path $fileAuth = Auth::user()->name; // Build the file path $filePath = "upload/team/".$fileAuth; $finalPath = storage_path("app/".$filePath);

    // move the file name
    $file->move($finalPath, $fileName);
    $file = new File;
    $file->filename = storage_path("app/".$filePath).'/'.$fileName;
    $file->save();
    return response()->json([
        'path' => $filePath,
        'name' => $fileName
    ]);
}

Please or to participate in this conversation.