Files

Files provides a simple way to handle file uploads and file delivery inside SigmaPHP. It focuses on managing uploaded files, basic storage operations, and returning files through the response system.

Uploaded files are stored inside the application storage directory and exposed publicly through a symbolic link.

Creating the Uploads Directory

Before working with uploads, create the uploads directory using the CLI command:


./bin/sigma-cli create:uploads
    

This command creates the storage/uploads directory and a symbolic link inside the public folder, allowing uploaded files to be accessed safely.

By default, uploaded files are stored inside the uploads directory. This location can be customized through the application configuration by updating the upload_path option in the app config file.


/**
 * Uploaded files path.
 */
'upload_path' => env('UPLOADS_PATH', 'storage/uploads'),
    

Uploading a File

File uploads allow users to send files from the browser to the application using a standard multipart form request. The Files utility handles saving the uploaded file into the configured uploads storage.


public function uploadFile(Request $request)
{
    if ($request->method() == 'POST') {
        $this->files()->save($request->files('my_file'));
        $this->flash('success', 'File was saved successfully !');
        return $this->route('index');
    }

    return $this->render('file');
}
    

You can then connect the action defined above to a form within your view as shown below.


<form action="{{ url('upload_file') }}" method="post" enctype="multipart/form-data">
    <input type="file" name="my_file" />
    <button type="submit">Upload</button>
</form>
    

When working with HTML forms that handle file uploads, make sure to include the enctype="multipart/form-data" attribute in your form.

Checking Uploaded Files

The has() method can be used to verify whether a file was uploaded before and exists in the storage.


$this->file->has('docs/book.pdf'); // true or false
    

Accessing Uploaded Files

In order to retrieve stored uploads and serve them to the browser as a response, making them available for inline viewing or download depending on the response headers.


public function returnFile()
{
    return $this->response(
        $this->files()->get('test.pdf'),
        'application/pdf',
        200,
        [
            'Content-Disposition' => 'inline;filename="test.pdf"'
        ]
    );
}
    

Uploaded files can be accessed directly inside your views using the global asset directive combined with the uploads directory. This allows you to reference stored files using a clean and consistent URL.


<img src="{% asset('uploads/avatar.jpeg') %}" alt="avatar"/>
    
Back to top