Laravel / Laravel Forms and Validation

Uploading Files with Laravel Forms

This tutorial will guide you through the process of uploading files in Laravel using forms. You will learn how to handle file inputs, validate them and store them in your applicat…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores handling form submissions and validating data in Laravel applications.

Introduction

In this tutorial, our main goal is to learn how to upload files using Laravel forms. We will be looking into handling file inputs, validating them, and finally storing them in our Laravel application. By the end of this tutorial, you will be able to create a form in Laravel that can upload files, validate file inputs, and store the file in your server.

Before we start, ensure that you have a basic understanding of PHP, Laravel, and HTML forms. Knowledge of MVC (Model-View-Controller) architecture will also be beneficial.

Step-by-Step Guide

File Inputs

In Laravel, you can handle file inputs using the file method on the Request instance. This method will return an instance of Illuminate\Http\UploadedFile, which extends the PHP SplFileInfo class and provides various methods for interacting with the file.

Let's say we have a form that contains a file input:

<form action="/upload" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="photo">
    <input type="submit" value="Upload">
</form>

To retrieve the file from the request, we can use the file method:

$photo = $request->file('photo');

Validation

Before storing the file, you may want to validate it. Laravel provides several validation rules for files, including file, image, mimes, and size.

Here's how you can validate that the uploaded file is an image and does not exceed 2048 kilobytes:

$request->validate([
    'photo' => 'required|image|max:2048',
]);

Storing Files

After validating the file, you can store it using the store method:

$path = $request->file('photo')->store('photos');

By default, this method will store the file in the storage/app directory. If you want to specify a different disk, you can use the storeOn method:

$path = $request->file('photo')->storeOn('s3', 'photos');

Code Examples

Let's put everything together in a controller method:

use Illuminate\Http\Request;

class PhotoController extends Controller
{
    public function upload(Request $request)
    {
        // Validate the request
        $request->validate([
            'photo' => 'required|image|max:2048',
        ]);

        // Store the photo
        $path = $request->file('photo')->store('photos');

        // Return the path
        return $path;
    }
}

In this method, we first validate the request. If the validation fails, Laravel will automatically redirect the user back to the form and flash the error messages to the session.

Next, we store the photo in the storage/app/photos directory. The store method returns the path of the stored file, which we then return.

Summary

In this tutorial, we learned how to upload files using Laravel forms. We started by handling file inputs using the file method on the Request instance. Then, we validated the file input using the validate method. Finally, we stored the file using the store method.

For further learning, you can explore other ways to store files, such as storing them on an external disk like Amazon S3.

Practice Exercises

  1. Create a form that allows users to upload multiple photos at once. Modify the upload method to handle multiple files.

  2. Add more validation rules to the upload method. For example, you can restrict the file types to jpeg and png, and set a minimum file size.

  3. Instead of storing the file in the storage/app/photos directory, store it in a public directory that can be accessed directly from the web.

Remember to test your code thoroughly after each change. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Image Converter

Convert between different image formats.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help