In this tutorial, we will explore how to handle file uploads and manage files in Laravel. This is an essential skill for developers working on web applications that involve user-generated content, such as images, documents, or any other file type.
You will learn how to:
- Handle file upload requests from users
- Store uploaded files in Laravel
- Retrieve, update, and delete files
Prerequisites: Familiarity with Laravel framework and basic PHP programming is recommended. Knowledge of HTML forms is also helpful.
Laravel makes handling file uploads incredibly easy. It provides a convenient API to handle file uploads and perform operations like moving the file, renaming it, getting its size or extension, etc.
The first step is to create a form that includes an input of type file
.
<form action="/upload" method="post" enctype="multipart/form-data">
@csrf
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
In the controller, Laravel provides the file
method on the Request
object to access the uploaded file.
$file = $request->file('fileToUpload');
Laravel provides the store
method to store the uploaded file in a disk. Here's how you can store a file in the public
disk.
$path = $request->file('fileToUpload')->store('images', 'public');
Let's look at a complete example of handling a file upload request.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function upload(Request $request)
{
// Validate the request...
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
// Store the file and get the path
$path = $request->file('fileToUpload')->store('images', 'public');
// Return the path
return $path;
}
}
In this example, we first validate the request to make sure a file is uploaded and its size doesn't exceed 1MB. Then we store the file in the public
disk under the images
directory and return the path of the stored file.
After a file is stored, you can retrieve it using the get
method of the Storage
facade.
$content = Storage::get('file.jpg');
To update a file, you can use the put
method of the Storage
facade.
Storage::put('file.jpg', $contents);
To delete a file, use the delete
method of the Storage
facade.
Storage::delete('file.jpg');
In this tutorial, you learned how to handle file uploads in Laravel, including storing, retrieving, updating, and deleting files.
The next step is to practice what you've learned. Try to build a simple application that allows users to upload, view, update, and delete files.
For further reading, you can check out the File Storage section in the official Laravel documentation.
Tips for further practice: Try integrating with cloud storage services like Amazon S3. Laravel supports these services out of the box and it's a common requirement in real-world applications.