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:
- Prerequisites
- Install Laravel
- Understanding How Laravel Handles Files
- Local and Public Disks
- Retrieving Files
- Storing File
- File Uploads
- File Visibility
- Deleting Files
- 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.php
you’ll see the disks and their respected configuration.
Local and Public Disks
In confit/filesystems.php
you 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/public
and Laravel’s server root
is in public, you need to link storage/app/public
to 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;
Storage::get('onlinecode.jpg');
Exists File
The exists
method 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.
Storage::url('onlinecode.jpg');
Temporary generate URL, you can use temporaryUrl:
Storage::temporaryUrl(
'onlinecode.jpg', now()->addMinutes(5)
);
File Metadata
The size
method used to get the size of a file in bytes:
Storage::size('onlinecode.jpg');
The lastModified
the method returns the UNIX timestamp of the last time the file was modified:
Storage::lastModified('onlinecode.jpg');
File Path
The path
method to get the path for a file:
Storage::path('onlinecode.jpg');
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 prepend
and append
methods 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 move
method 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 store
method with the path at which you wish to store the uploaded file:
<?php
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 putFile
method on the Storage
facade to perform the same file storage operation as the example above:
$path = Storage::putFile('sslforweb', $request->file('onlinecode'));
Specifying A File Name
The storeAs
method, which receives the path, the filename, and the (optional) disk as its arguments:
$path = $request->file('onlinecode')->storeAs(
'sslforweb', $request->user()->id
);
The putFileAs
method on the Storage
facade, 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 store
method, If you would like to specify another disk, pass the disk name as the second argument.
$path = $request->file('onlinecode')->store(
'sslforweb/'.$request->user()->id,
's3'
);
The storeAs
method if you are using, passes the disk name as the third argument.
$path = $request->file('onlinecode')->storeAs(
'sslforweb',
$request->user()->id,
's3'
);
Other Uploaded File Information
To get the original name of the uploaded file, you can use the getClientOriginalName
method:
$originalFileName = $request->file('onlinecode')->getClientOriginalName();
The extension
method 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 public
or 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 public
files.
You can set the visibility when writing the file via the put
method:
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 storePublicly
and storePubliclyAs
methods to store the uploaded file with public visibility:
$path = $request->file('onlinecode')->storePublicly('sslforweb', 's3');
$path = $request->file('onlinecode')->storePubliclyAs(
'sslforweb',
$request->user()->id,
's3'
);
Local files & Visibility
The local
driver, 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 delete
method accepts a single filename or an array of files to delete:
Storage::delete('onlinecode.jpg');
Storage::delete(['onlinecode.jpg', 'sslforweb.jpg']);
You may specify the disk that the file should be deleted from:
Storage::disk('s3')->delete('path/onlinecode.jpg');
Also see: How to Use Alpine JS with Laravel
Directories
Get All Files Within A Directory
The files
method 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 allFiles
method:
$files = Storage::files($directory);
$files = Storage::allFiles($directory);
Get All Directories Within A Directory
The directories
method returns an array of all the directories within a directory. You may use the allDirectories
method 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 makeDirectory
method will create the directory, including any needed subdirectories:
Storage::makeDirectory($directory);
Delete A Directory
The deleteDirectory
method may remove a directory and all of its files:
Storage::deleteDirectory($directory);
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