robertvrabel's avatar

My own File model conflicting with Illuminate's file facade

Having a discussion about conflicting facades from Laravel with your own App\Model.

Example:

App\File - A model for our app to save files to the DB and to the server using Storage

In App\File We're importing \Illuminate\Support\Facades\File and calling File::get('file') to interact with the uploaded file using the Illuminate File facade.

What is the proper way to handle this conflict since our Model is also called file? Are we supposed to rename ours? Change their facade? Not use the facade in this file and reference it straight up? Looking for the best practice here.

0 likes
5 replies
robertvrabel's avatar

@martinbean Where would the proper place for that go? I debated putting it into a Controller. But I want to use that code from multiple different controllers. So it didn't make sense for me to initiate my FilesController class within another controller. Wasn't sure where it would go.

I'm pretty new to laravel, so if you have any suggestions on where code like this should go so I can reuse it all over would be great.

If its helpful, here is the code I have within the App\File model to save the file to the server and save it to the DB.

    /**
     * Save the file, so the reference location is in one spot.
     *
     * @param UploadedFile $file
     * @return int
     */
    public function saveFile(UploadedFile $file)
    {
        // Format filename
        $this->attributes['filename'] = $this->formatFileName($file->getClientOriginalName());

        // Save to storage
        Storage::disk($_SERVER['APP_ENV'])->put($this->dir . $this->attributes['filename'], IlluminateFile::get($file));

        // Return false if the Save Fails
        if(!$this->save()){
            return false;
        }

        // File saved, return true
        return true;
    }
jekinney's avatar

I agree, if your going to reuse the method it definitely doesn't belong in the controller.

If the file is under the app directory and namespace it differently (as you mentioned different folders) it will not be an issue. Just be careful in your use statement that you reference the correct class. Also you can import the illuminate file by simply use File;

martinbean's avatar

@robertvrabel It’s probably best being wrapped up in a service class. You would instantiate the service class in your controller, pass the request parameters to it, and then it would handle both the file uploading and saving to the database via the model.

public function create(Request $request)
{
    $service = new CreateFileService;
    $service->execute($request->all());
}
class CreateFileService
{
    public function execute(array $data)
    {
        // Handle file upload
        // Save record to database
    }
}

This way, your logic’s wrapped up in a single class that can then be re-used.

Please or to participate in this conversation.