Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel storeas()
laravel
php
communitycreator

How to perform a file upload on your website

Chinweuba Elijah Azubuike
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.

RELATED TAGS

laravel storeas()
laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring