Understanding and Working with Files in Laravel

Understanding and Working with Files in Laravel

In this post we will give you information about Understanding and Working with Files in Laravel. Hear we will give you detail about Understanding and Working with Files in Laravel And how to use it also give you demo for it if it is necessary.

In modern web development , file uploads are one of the most commonly used features and Laravel Storage provides an intuitive way to handle the file storage. A framework-agnostic filesystem package with multiple adapters like AwsS3 and Dropbox . By default, Laravel Zero ships with the Filesystem component of Laravel.

Table of contents:

  1. Prerequisites
  2. Install Laravel
  3. Understanding How Laravel Handles Files
  4. Local and Public Disks
  5. Retrieving Files
  6. Storing File
  7. File Uploads
  8. File Visibility
  9. Deleting Files
  10. Directories


Let’s look at these technologies:

Install Laravel

 To get started, create a Laravel application. To do this, run the following command in your terminal:

composer create-project laravel/laravel filesystem

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new filesystem

Understanding How Laravel Handles Files

Development, as we know it in 2018, is growing fast, and in most cases, there are many solutions to one problem. Take file hosting, for example, now we have so many options to store files, the sheer number of solutions ranging from self-hosted to FTP to cloud storage to GFS and many others.

Laravel’s solution to this problem is to call them disks. Makes sense, any file storage system you can think of can be labeled as a disk in Laravel. Laravel comes with native support for some providers (disks). We have local, public, s3, Rackspace, FTP, etc. All this is possible because of the filesystem.

If you open config/filesystems.phpyou’ll see the disks and their respected configuration.

Local and Public Disks

In confit/filesystems.phpyou can see the disks local and public defined. By default, Laravel uses the local disk configuration. The major difference between local and the public disk is that local is private and cannot be accessed from the browser while it can access public from the browser. Therefore, the following method would write to storage/app/example.txt:

use Storage;

Storage::disk('local')->put('onlinecode.txt', 'Any Contents');

Since the public disk is in storage/app/publicand Laravel’s server rootis in public, you need to link storage/app/publicto Laravel’s public folder. Run the following command:

php artisan storage:link

Also see:   How to use Tailwind CSS with Laravel

Retrieving Files

Get File

The get method used to retrieve the contents of the file:

use Storage;

Exists File

The existsmethod used if a file exists on the disk:

if (Storage::disk('local')->exists('onlinecode.jpg')) {
    // ...
Missing File

The missing the method used if a file missing from the disk:

if (Storage::disk('local')->missing('onlinecode.jpg')) {
    // ...
Downloading File

The download the method used to generate a response that forces the user’s browser to download the file on the path:

return Storage::download('onlinecode.jpg');

The download the method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

return Storage::download('onlinecode.jpg', $name, $headers);
Generate URLs

The url the method used to generate URL for the user.


Temporary generate URL, you can use temporaryUrl:

    'onlinecode.jpg', now()->addMinutes(5)
File Metadata

The sizemethod used to get the size of a file in bytes:


The lastModified the method returns the UNIX timestamp of the last time the file was modified:

File Path

The pathmethod to get the path for a file:


Storing File

The put method may store file contents on a disk:

Storage::put('onlinecode.jpg', $contents);

Storage::put('onlinecode.jpg', $resource);
Prepending & Appending to Files

The prependand appendmethods write to the beginning or end of a file:

Storage::prepend('prepend.log', 'Prepended Text');

Storage::append('append.log', 'Appended Text');
Copying & Moving Files

The copy method may copy an existing file to a new location on the disk, and the movemethod may rename or move an existing file to a new location:

Storage::copy('file_path', 'destination_path');

Storage::move('file_path', 'destination_path');

File Uploads

Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can select a file to be uploaded and a controller where uploaded files will be processed.

Call the storemethod with the path at which you wish to store the uploaded file:


namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;

class FileController extends Controller
     * Update the name for the file.
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
    public function update(Request $request)
        $path = $request->file('onlinecode')->store('sslforweb');

        return $path;

You may also call the putFilemethod on the Storagefacade to perform the same file storage operation as the example above:

$path = Storage::putFile('sslforweb', $request->file('onlinecode'));
Specifying A File Name

The storeAsmethod, which receives the path, the filename, and the (optional) disk as its arguments:

$path = $request->file('onlinecode')->storeAs(
    'sslforweb', $request->user()->id

The  putFileAsmethod on the Storagefacade, which will perform the same file storage operation as the example above:

$path = Storage::putFileAs(
    'sslforweb', $request->file('onlinecode'), $request->user()->id
Specifying A Disk

By default use storemethod, If you would like to specify another disk, pass the disk name as the second argument.

$path = $request->file('onlinecode')->store(

The storeAsmethod if you are using, passes the disk name as the third argument.

$path = $request->file('onlinecode')->storeAs(
Other Uploaded File Information

To get the original name of the uploaded file, you can use the getClientOriginalNamemethod:

$originalFileName = $request->file('onlinecode')->getClientOriginalName();

The extensionmethod may get the file extension of the uploaded file:

$fileExtension = $request->file('onlinecode')->extension();

File Visibility

In Laravel’s Flysystem integration, “visibility” is an abstraction of file permissions across multiple platforms. Files may either be declared publicor private. When a file is declared public, you show the file should be accessible to others. For example, when using the S3 driver, you may retrieve URLs for publicfiles.

You can set the visibility when writing the file via the putmethod:

Storage::put('onlinecode.jpg', $contents, 'public');

The getVisibility and setVisibility methods: If the file has already been stored, its visibility can be retrieved and set.

$getFileVisibility = Storage::getVisibility('onlinecode.jpg');

Storage::setVisibility('onlinecode.jpg', 'public');

The storePubliclyand storePubliclyAsmethods to store the uploaded file with public visibility:

$path = $request->file('onlinecode')->storePublicly('sslforweb', 's3');

$path = $request->file('onlinecode')->storePubliclyAs(
Local files & Visibility

The localdriver, public visibility translates to 0755 permissions for directories and 0644 permissions for files. You can change the permissions mappings in your application’s filesystems configuration file:

'local' => [
    'driver' => 'local',
    'root' => storage_path('app'),
    'permissions' => [
        'file' => [
            'public' => 0664,
            'private' => 0600,
        'dir' => [
            'public' => 0775,
            'private' => 0700,

Deleting Files

The deletemethod accepts a single filename or an array of files to delete:


Storage::delete(['onlinecode.jpg', 'sslforweb.jpg']);

You may specify the disk that the file should be deleted from:


Also see:   How to Use Alpine JS with Laravel


Get All Files Within A Directory

The filesmethod returns an array of all the files in a directory. If you would like to retrieve a list of all files within a directory including all subdirectories, you may use the allFilesmethod:

$files = Storage::files($directory);

$files = Storage::allFiles($directory);
Get All Directories Within A Directory

The directoriesmethod returns an array of all the directories within a directory. You may use the allDirectoriesmethod to get a list of all directories within a directory and all of its subdirectories:

directories = Storage::directories($directory);

$allDirectories = Storage::allDirectories($directory);
Create A Directory

The makeDirectorymethod will create the directory, including any needed subdirectories:

Delete A Directory

The deleteDirectorymethod may remove a directory and all of its files:


Thank you for reading this blog.

Also see:  How to Send an Email in Laravel

If you have any queries or doubts about this topic please feel free to  contact us . We will try to reach you.

Hope this code and post will helped you for implement Understanding and Working with Files in Laravel. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US