How to perform a file upload on your website

widget

Overview

Performing a file upload can range from a user uploading pictures alongside articles, updating their profile picture, or sending documents. This is a crucial aspect of a web application, and Laravel makes it very easy.

Syntax

$path = $request->file('avatar')->storeAs(
    'avatars', $request->user()->id
);

Parameters

The storeAs() method receives two parameters:

  1. The path (the directory you wish to put the file).

  2. The file name(in our case, we use the user id).

Explanation

In the syntax above, we call the storeAs() method on the $request->file(), which receives the file from the form. Then, we chain it with the storeAs() method.

storeAs(), as explained in the parameters section, receives two parameters. The first one is the name of the directory/folder in your application that you want to put the file in, and the second is the name you want to store the file as.

Example

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserAvatarController extends Controller
{
    

    public function update(Request $request)
    {
        $path = $request->file('avatar')->storeAs('avatars',$request->user()->id);

        return $path;
    }
}

Code explanation

The above example shows how we store a file avatar to the avatars directory in our application and save the file name as the user id. We finally return the $path, which you can store into your database if you choose to do so.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources