0
0
LaravelHow-ToBeginner · 3 min read

How to Use Storage Facade in Laravel: Simple Guide

Use Laravel's Storage facade to interact with filesystems like local or cloud storage. Call methods like Storage::put() to save files and Storage::get() to read files easily within your Laravel app.
📐

Syntax

The Storage facade provides simple methods to work with files. Common methods include:

  • Storage::put('filename', 'content') - saves content to a file.
  • Storage::get('filename') - reads content from a file.
  • Storage::exists('filename') - checks if a file exists.
  • Storage::delete('filename') - deletes a file.

You can specify disks like local, s3, etc., by calling Storage::disk('diskname').

php
use Illuminate\Support\Facades\Storage;

// Save a file
Storage::put('example.txt', 'Hello Laravel');

// Read a file
$content = Storage::get('example.txt');

// Check if file exists
$exists = Storage::exists('example.txt');

// Delete a file
Storage::delete('example.txt');

// Use specific disk
Storage::disk('s3')->put('example.txt', 'Hello S3');
💻

Example

This example shows how to save a text file, check if it exists, read its content, and then delete it using the Storage facade.

php
<?php

use Illuminate\Support\Facades\Storage;

// Save file
Storage::put('greeting.txt', 'Hello from Laravel Storage!');

// Check if file exists
if (Storage::exists('greeting.txt')) {
    // Read file content
    $content = Storage::get('greeting.txt');
    echo $content; // Outputs: Hello from Laravel Storage!

    // Delete file
    Storage::delete('greeting.txt');
} else {
    echo 'File not found.';
}
Output
Hello from Laravel Storage!
⚠️

Common Pitfalls

Common mistakes when using the Storage facade include:

  • Not configuring the filesystem disks properly in config/filesystems.php.
  • Forgetting to run php artisan storage:link to create a symbolic link for public storage.
  • Using wrong disk names or forgetting to specify the disk when needed.
  • Assuming files are publicly accessible without proper linking or permissions.
php
// Wrong: Trying to access a file without specifying disk when it's on s3
Storage::get('file.txt'); // May fail if default disk is local

// Right: Specify disk explicitly
Storage::disk('s3')->get('file.txt');
📊

Quick Reference

MethodDescription
put('filename', 'content')Save content to a file
get('filename')Read content from a file
exists('filename')Check if a file exists
delete('filename')Delete a file
disk('diskname')Specify which disk to use

Key Takeaways

Use the Storage facade methods like put, get, exists, and delete to manage files easily.
Specify the disk with Storage::disk('name') when working with different storage systems.
Configure filesystem disks properly in config/filesystems.php before using Storage.
Run php artisan storage:link to make local storage files publicly accessible.
Always check if a file exists before reading or deleting it to avoid errors.