Understanding and Working with Files in Laravel - TechvBlogs

Understanding and Working with Files in Laravel

File uploads are one the most commonly used features on the web. From uploading avatars to family pictures to sending documents via email, we can't do without files on the web.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

1 year ago

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

Prerequisites

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('techvblogs.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

Read Also:   How to use Tailwind CSS with Laravel

Retrieving Files

Get File

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

use Storage;

Storage::get('techvblogs.jpg');
Exists File

The existsmethod used if a file exists on the disk:

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

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

if (Storage::disk('local')->missing('techvblogs.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('techvblogs.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('techvblogs.jpg', $name, $headers);
Generate URLs

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

Storage::url('techvblogs.jpg');

Temporary generate URL, you can use temporaryUrl:

Storage::temporaryUrl(
    'techvblogs.jpg', now()->addMinutes(5)
);

File Metadata

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

Storage::size('techvblogs.jpg');

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

Storage::lastModified('techvblogs.jpg');
File Path

The pathmethod to get the path for a file:

Storage::path('techvblogs.jpg');

Storing File

The put method may store file contents on a disk:

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

Storage::put('techvblogs.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:

<?php

namespace App\Http\Controllers;

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

class FileController extends Controller
{
    /**
     * Update the name for the file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $path = $request->file('techvblogs')->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('techvblogs'));
Specifying A File Name

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

$path = $request->file('techvblogs')->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('techvblogs'), $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('techvblogs')->store(
    'sslforweb/'.$request->user()->id, 
    's3'
);

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

$path = $request->file('techvblogs')->storeAs(
    'sslforweb',
    $request->user()->id,
    's3'
);
Other Uploaded File Information

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

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

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

$fileExtension = $request->file('techvblogs')->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('techvblogs.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('techvblogs.jpg');

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

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

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

$path = $request->file('techvblogs')->storePubliclyAs(
    'sslforweb',
    $request->user()->id,
    's3'
);

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('techvblogs.jpg');

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

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

Storage::disk('s3')->delete('path/techvblogs.jpg');

Read Also:   How to Use Alpine JS with Laravel

Directories

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:

Storage::makeDirectory($directory);
Delete A Directory

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

Storage::deleteDirectory($directory);

Thank you for reading this blog.

Read Also:  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.

Comments (0)

ServerAvatar
Multiple sites on a single VPS/VM/Server Deploy PHP sites on cloud in minutes, simple as that!
ServerAvatar
Generate Free SSL Certificate - SSLForWeb

Generate Free SSL Certificate

  • 90-Day Certificates
  • SSL Monitoring
  • Wildcard Certificates
  • Multiple Domains
  • Certificate Management
  • Expiration Reminders

Comment


Note: All Input Fields are required.