Reading writing and deleting a File from disk or filesystem in Laravel 5

An Introduction To Laravel's FileSystem

An Introduction To Laravel’s FileSystem

Laravel uses Frank de Jonge PHP Package For managing Filesystem.Laravel provides simple drivers to manage local filesystem, Amazon S3, and Rackspace Cloud Storage.You can easily switch between these filesystems with no change in API’s.

Configuration

Laravel makes Filesystem configuration is an easy task, the configuration of filesystem is located at config/filesystems.php . Within this file, you can configure your all disks local or remote.Each disk represents a particular storage driver and storage location.

In this post, we are going to see how to Read, Write and Delete a file from local filesystem in Laravel5

In Laravel by Default, Filesystem Disk is set to local. to Read, Write and Delete a file from local filesystem in Laravel5 you need to make any changes in config/filesystems.php.

Writing a file from Local Disk

When you are using the local driver, all file operations are relative to the root directory defined in your configuration file. By default, this value is set to the storage/app directory. Therefore, the following method would store a file in storage/app/file.txt:

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

Reading a file from Local Disk

In order to read a file from local disk Storage::get() method is used. get method takes the name of the file and returns its content.Below is sample usage.

$contents = Storage::get('file.jpg');

Getting Relative URL or Path of a file in Laravel

use IlluminateSupportFacadesStorage;

$url = Storage::url('file1.jpg');

Copying & Moving Files

Storage::copy('old/file1.jpg', 'new/file1.jpg');

Storage::move('old/file1.jpg', 'new/file1.jpg');

Storing an uploaded file in disk

$path = $request->file('avatar')->store('avatars');

Deleting or removing a file from Local Disk

The delete method is used for Deleting or removing a file from Disk. Delete method accepts a single filename or an array of files to remove from the disk. Below is usage guide.

use IlluminateSupportFacadesStorage;

Storage::delete('file.jpg');

Leave a Reply

Your email address will not be published. Required fields are marked *