File Storage
- Introduction
- Configuration
- Obtaining disk instances
- Retrieving files
- Storing files
- Deleting files
- Directories
- Testing
Introduction
Applications store many kinds of files: user avatars, generated invoices, and nightly report exports. The laravel::storage module provides a unified API across local filesystems, Laravel Cloud Object Storage, and S3-compatible object stores, so your code reads and writes files identically whether they live locally or in the cloud.
Configuration
Files live on named disks, where each disk maps to either a local directory or an S3-compatible bucket. The FILESYSTEM_DISK environment variable selects the default disk used by top-level functions in laravel::storage. Laravel configures three disks out of the box:
| Disk | Location | Access |
|---|---|---|
local |
storage/app/private (default disk). |
Your handlers and temporary URLs. |
public |
storage/app/public. |
Publicly downloadable from /storage. |
s3 |
Bucket configured via AWS_* variables. |
Controlled by your bucket policy. |
Most applications only need these built-in disks. To add another disk, create a src/config/filesystems.rs configuration file starting from Filesystems::from_env and register your disk. Local disk roots are resolved relative to your application's base path:
1// src/config/filesystems.rs2use laravel::config::filesystems::{Filesystems, LocalDisk};3use laravel::config::{self, Env};45#[config::section]6fn filesystems(env: &Env) -> Filesystems {7 let mut filesystems = Filesystems::from_env(env);89 filesystems.add_disk("documents", LocalDisk::new("storage/app/documents"));1011 filesystems12}1// src/config/filesystems.rs2use laravel::config::filesystems::{Filesystems, LocalDisk};3use laravel::config::{self, Env};45#[config::section]6fn filesystems(env: &Env) -> Filesystems {7 let mut filesystems = Filesystems::from_env(env);89 filesystems.add_disk("documents", LocalDisk::new("storage/app/documents"));1011 filesystems12}
Register the module in src/config/mod.rs:
1mod filesystems;1mod filesystems;
The public disk
The public disk stores files intended to be publicly accessible, such as user avatars. Laravel serves its files directly at /storage, so a file stored at avatars/1.png is served at https://example.com/storage/avatars/1.png.
Custom local disks are not served over HTTP until you assign a mount path. With only a mount path, files can only be downloaded via temporary URLs. Chain .public() to allow direct public downloads as well:
1filesystems.add_disk(2 "images",3 LocalDisk::new("storage/app/images").mount("/images").public(),4);56filesystems.add_disk(7 "documents",8 LocalDisk::new("storage/app/documents").mount("/documents"),9);1filesystems.add_disk(2 "images",3 LocalDisk::new("storage/app/images").mount("/images").public(),4);56filesystems.add_disk(7 "documents",8 LocalDisk::new("storage/app/documents").mount("/documents"),9);
With this configuration, a file stored at banners/hero.png on the images disk is served publicly at https://example.com/images/banners/hero.png, while files on the documents disk are only accessible under /documents via signed temporary URLs.
If one of your application routes matches the same path as a disk mount, your route takes precedence.
Laravel Cloud Object Storage
When deploying to Laravel Cloud, store uploaded and generated files in Laravel Cloud Object Storage buckets instead of the local filesystem, since container disks are reset on each deploy and aren't shared across instances. Laravel Cloud Object Storage works out of the box with no extra Cargo features or AWS SDK dependency.
When you attach a bucket to an environment in the Laravel Cloud dashboard, Laravel registers it automatically under the disk name you chose. That replaces any built-in disk with the same name (such as local or public), so your application can keep using local disks in development and switch to Cloud buckets in production without changing your code. If you mark a bucket as the environment's default disk in the dashboard, top-level laravel::storage calls target that bucket automatically.
A bucket's visibility applies to all of its files. Files in a public bucket have public URLs served from the bucket's public domain, while files in a private bucket are only accessible through signed temporary URLs (valid for up to seven days). If your application stores both public and private files, attach a private bucket as the default disk and a public bucket named public.
To connect to a Laravel Cloud bucket from outside Laravel Cloud, such as during local development, register a LaravelCloudDisk in src/config/filesystems.rs using the bucket name, endpoint, and access keys from the dashboard (omit .public_url(..) for a private bucket):
1// src/config/filesystems.rs2use laravel::config::filesystems::LaravelCloudDisk;34filesystems.add_disk(5 "avatars",6 LaravelCloudDisk::new(7 "avatars",8 env.get::<String>("CLOUD_BUCKET_ENDPOINT").unwrap_or_default(),9 env.get::<String>("CLOUD_BUCKET_KEY").unwrap_or_default(),10 env.get::<String>("CLOUD_BUCKET_SECRET").unwrap_or_default(),11 )12 .public_url("https://avatars.laravel.cloud"),13);1// src/config/filesystems.rs2use laravel::config::filesystems::LaravelCloudDisk;34filesystems.add_disk(5 "avatars",6 LaravelCloudDisk::new(7 "avatars",8 env.get::<String>("CLOUD_BUCKET_ENDPOINT").unwrap_or_default(),9 env.get::<String>("CLOUD_BUCKET_KEY").unwrap_or_default(),10 env.get::<String>("CLOUD_BUCKET_SECRET").unwrap_or_default(),11 )12 .public_url("https://avatars.laravel.cloud"),13);
S3-compatible disks
To store files in Amazon S3 or any S3-compatible object store, enable Laravel's s3 Cargo feature in Cargo.toml:
1[dependencies]2laravel-rust = { version = "0.1", features = ["s3"] }1[dependencies]2laravel-rust = { version = "0.1", features = ["s3"] }
Next, set the AWS_* variables in your .env file. If you omit the access key and secret, the disk falls back to the AWS SDK's default credential chain, such as an EC2 or ECS IAM role:
1FILESYSTEM_DISK=s323AWS_ACCESS_KEY_ID=your-key4AWS_SECRET_ACCESS_KEY=your-secret5AWS_DEFAULT_REGION=us-east-16AWS_BUCKET=your-bucket1FILESYSTEM_DISK=s323AWS_ACCESS_KEY_ID=your-key4AWS_SECRET_ACCESS_KEY=your-secret5AWS_DEFAULT_REGION=us-east-16AWS_BUCKET=your-bucket
The s3 disk works with any S3-compatible service, including Cloudflare R2, DigitalOcean Spaces, and MinIO. Set AWS_ENDPOINT to your provider's endpoint, and enable AWS_USE_PATH_STYLE_ENDPOINT for providers such as MinIO that require path-style URLs:
1AWS_ENDPOINT=https://objects.example.com2AWS_USE_PATH_STYLE_ENDPOINT=true3AWS_URL=https://cdn.example.com1AWS_ENDPOINT=https://objects.example.com2AWS_USE_PATH_STYLE_ENDPOINT=true3AWS_URL=https://cdn.example.com
AWS_URL sets the base URL for public file URLs, such as a CDN domain. Your bucket's policy controls whether files are publicly readable; Laravel never alters object ACLs, so generating a public URL for a private bucket does not expose the file.
To configure an additional S3 bucket, add an S3Disk in src/config/filesystems.rs. You may chain credentials, endpoint, path_style, and public_url to customize the disk:
1use laravel::config::filesystems::S3Disk;23filesystems.add_disk(4 "documents",5 S3Disk::new("acme-documents", "eu-west-1")6 .credentials(7 env.get::<String>("DOCS_AWS_ACCESS_KEY_ID").unwrap_or_default(),8 env.get::<String>("DOCS_AWS_SECRET_ACCESS_KEY").unwrap_or_default(),9 )10 .endpoint("https://objects.example.com")11 .path_style()12 .public_url("https://documents.example.com"),13);1use laravel::config::filesystems::S3Disk;23filesystems.add_disk(4 "documents",5 S3Disk::new("acme-documents", "eu-west-1")6 .credentials(7 env.get::<String>("DOCS_AWS_ACCESS_KEY_ID").unwrap_or_default(),8 env.get::<String>("DOCS_AWS_SECRET_ACCESS_KEY").unwrap_or_default(),9 )10 .endpoint("https://objects.example.com")11 .path_style()12 .public_url("https://documents.example.com"),13);
Read-through disks
When migrating files from one disk to another (such as moving from local storage to S3), a read-through disk lets your application stay online during the transition. Reads check the primary disk first and fall back to the secondary disk on a miss, while writes always target the primary disk:
1use laravel::config::filesystems::ReadThroughDisk;23filesystems.add_disk("uploads", ReadThroughDisk::new("s3", "local"));1use laravel::config::filesystems::ReadThroughDisk;23filesystems.add_disk("uploads", ReadThroughDisk::new("s3", "local"));
By default, when a read hits the fallback disk, Laravel copies the file to the primary disk so future reads are served from there. If that promotion copy fails, the read still succeeds unless you chain .throw_on_promotion_failure(). To disable automatic promotion altogether, chain .without_promotion().
Deleting a file removes it from both disks so stale copies cannot resurface from the fallback.
Obtaining disk instances
Top-level functions in laravel::storage operate on your default disk. For example, this handler writes a CSV report to the default disk:
1use laravel::prelude::*;2use laravel::storage;34pub async fn store() -> laravel::Result<Redirect> {5 storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?;67 Ok(Redirect::back())8}1use laravel::prelude::*;2use laravel::storage;34pub async fn store() -> laravel::Result<Redirect> {5 storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?;67 Ok(Redirect::back())8}
To target a specific disk, pass its name to storage::disk, which returns a disk handle with the same methods:
1storage::disk("s3")?2 .put("reports/monthly.csv", "name,total\nTaylor,42\n")3 .await?;1storage::disk("s3")?2 .put("reports/monthly.csv", "name,total\nTaylor,42\n")3 .await?;
Storage functions work anywhere your application runs, including handlers, console commands, and queued jobs. Paths are relative to the disk's root, so reports/monthly.csv on the local disk maps to storage/app/private/reports/monthly.csv. Paths starting with / or containing .. segments are rejected with storage::InvalidPath.
On-demand disks
When you need a disk that isn't defined in your configuration (such as a directory passed to a console command), build one dynamically with storage::build:
1use laravel::config::filesystems::LocalDisk;2use laravel::storage;34let imports = storage::build(LocalDisk::new("/var/imports"))?;56let orders = imports.get("orders.csv").await?;1use laravel::config::filesystems::LocalDisk;2use laravel::storage;34let imports = storage::build(LocalDisk::new("/var/imports"))?;56let orders = imports.get("orders.csv").await?;
On-demand local disks are not registered as HTTP mounts and cannot generate URLs, though they can still serve downloads. On-demand S3 disks can generate both public and temporary URLs as usual.
Retrieving files
Use storage::get to read a file's bytes, or storage::json to deserialize a JSON file into any type implementing Deserialize:
1use laravel::storage;2use serde::Deserialize;34#[derive(Deserialize)]5struct Settings {6 theme: String,7 notifications: bool,8}910let contents = storage::get("reports/monthly.csv").await?;1112let settings: Settings = storage::json("settings.json").await?;1use laravel::storage;2use serde::Deserialize;34#[derive(Deserialize)]5struct Settings {6 theme: String,7 notifications: bool,8}910let contents = storage::get("reports/monthly.csv").await?;1112let settings: Settings = storage::json("settings.json").await?;
Because get and json buffer the entire file in memory, they reject files larger than 8 MiB with storage::TooLarge. For larger files, raise the limit with get_with_limit or stream the file in chunks with read_stream:
1use laravel::storage;2use laravel::stream::TryStreamExt;34let contents = storage::get_with_limit("exports/orders.csv", 32 * 1024 * 1024)5 .await?;67let mut file = storage::read_stream("exports/orders.csv").await?;89while let Some(chunk) = file.stream.try_next().await? {10 // Process each chunk of bytes...11}1use laravel::storage;2use laravel::stream::TryStreamExt;34let contents = storage::get_with_limit("exports/orders.csv", 32 * 1024 * 1024)5 .await?;67let mut file = storage::read_stream("exports/orders.csv").await?;89while let Some(chunk) = file.stream.try_next().await? {10 // Process each chunk of bytes...11}
Check whether a file exists with storage::exists or storage::missing:
1if storage::exists("reports/monthly.csv").await? {2 // ...3}1if storage::exists("reports/monthly.csv").await? {2 // ...3}
Reading a missing file returns storage::NotFound. Returning that error directly from a handler produces a 500 response, since missing internal files usually indicate a bug. When a request specifies the filename, convert NotFound into a 404:
1use laravel::prelude::*;2use laravel::storage::{self, Bytes, NotFound};34pub async fn show(Params(name): Params<String>) -> laravel::Result<Bytes> {5 match storage::get(&format!("reports/{name}")).await {6 Err(error) if error.is::<NotFound>() => Err(laravel::abort(404)),7 contents => contents,8 }9}1use laravel::prelude::*;2use laravel::storage::{self, Bytes, NotFound};34pub async fn show(Params(name): Params<String>) -> laravel::Result<Bytes> {5 match storage::get(&format!("reports/{name}")).await {6 Err(error) if error.is::<NotFound>() => Err(laravel::abort(404)),7 contents => contents,8 }9}
Downloading files
Return storage::download from a handler to prompt the browser to save a file. By default, the browser uses the path's filename; chain .name(..) to customize it. To display a file inline in the browser (such as a PDF or image), use storage::response instead. Both return 404 if the file does not exist:
1use laravel::prelude::*;2use laravel::storage::{self, FileResponse};34use crate::models::User;56pub async fn invoice(7 user: Authenticated<User>,8 Params(id): Params<u64>,9) -> laravel::Result<FileResponse> {10 // Verify that the user is authorized to view this invoice...1112 Ok(storage::download(&format!("invoices/{id}.pdf"))?.name("Invoice.pdf"))13}1use laravel::prelude::*;2use laravel::storage::{self, FileResponse};34use crate::models::User;56pub async fn invoice(7 user: Authenticated<User>,8 Params(id): Params<u64>,9) -> laravel::Result<FileResponse> {10 // Verify that the user is authorized to view this invoice...1112 Ok(storage::download(&format!("invoices/{id}.pdf"))?.name("Invoice.pdf"))13}
Because downloads pass through your handler, you can authorize every request. Use download for private files such as invoices rather than exposing a public URL.
File URLs
Call url to get a file's public URL on the public disk, a custom local disk marked with .public(), a public Laravel Cloud bucket, or an S3 disk:
1use laravel::storage;23let url = storage::disk("public")?.url("avatars/1.png").await?;1use laravel::storage;23let url = storage::disk("public")?.url("avatars/1.png").await?;
On the public disk, this returns https://example.com/storage/avatars/1.png. On a public Laravel Cloud bucket, it returns a URL under the bucket's public domain. On an S3 disk, it uses AWS_URL if configured, or the bucket's URL otherwise.
Temporary URLs
To grant time-limited access to a private file, generate a signed temporary URL:
1use laravel::prelude::*;2use laravel::storage;34let url = storage::temporary_url("invoices/1.pdf", 5.minutes()).await?;1use laravel::prelude::*;2use laravel::storage;34let url = storage::temporary_url("invoices/1.pdf", 5.minutes()).await?;
On a local disk, Laravel signs the URL with APP_KEY and serves it from the disk's mount. On S3 and Laravel Cloud, the presigned URL directs the browser straight to your bucket.
You can also let browsers upload directly to a disk (avoiding routing large files like videos through your application server on S3 or Laravel Cloud) using temporary_upload_url, which returns the signed URL, HTTP method, and required headers:
1let upload = storage::temporary_upload_url("incoming/video.mp4", 5.minutes()).await?;23// Send upload.url, upload.method, and upload.headers to the browser...1let upload = storage::temporary_upload_url("incoming/video.mp4", 5.minutes()).await?;23// Send upload.url, upload.method, and upload.headers to the browser...
File metadata
Use size, last_modified, and mime_type to inspect individual attributes, or metadata to retrieve all three in one call:
1use laravel::storage;23let bytes = storage::size("reports/monthly.csv").await?;4let modified = storage::last_modified("reports/monthly.csv").await?;5let mime_type = storage::mime_type("reports/monthly.csv").await?;67let metadata = storage::metadata("reports/monthly.csv").await?;89let size = metadata.size;10let content_type = metadata.content_type;11let last_modified = metadata.last_modified;1use laravel::storage;23let bytes = storage::size("reports/monthly.csv").await?;4let modified = storage::last_modified("reports/monthly.csv").await?;5let mime_type = storage::mime_type("reports/monthly.csv").await?;67let metadata = storage::metadata("reports/monthly.csv").await?;89let size = metadata.size;10let content_type = metadata.content_type;11let last_modified = metadata.last_modified;
Because MIME types are inferred from the filename or reported by the storage backend rather than inspecting file bytes, do not rely on mime_type for security validation.
Storing files
Use storage::put to write a file, replacing any existing file at that path. It accepts owned or borrowed strings and byte slices. For example, this stores a CSV string and an avatar fetched via the HTTP client:
1use laravel::http::client;2use laravel::storage;34storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?;56let avatar = client::get("https://example.com/avatars/taylor.png")7 .ensure_successful()8 .await?;910storage::put("avatars/1.png", avatar.bytes()).await?;1use laravel::http::client;2use laravel::storage;34storage::put("reports/monthly.csv", "name,total\nTaylor,42\n").await?;56let avatar = client::get("https://example.com/avatars/taylor.png")7 .ensure_successful()8 .await?;910storage::put("avatars/1.png", avatar.bytes()).await?;
Streaming large files
put holds the full file in memory. For large files such as videos or database exports, use write_stream to stream chunks directly to storage as they arrive:
1use laravel::http::client;2use laravel::storage;34let export = client::get("https://partner.example.com/exports/orders.csv")5 .stream()6 .await?;78storage::disk("s3")?9 .write_stream("exports/orders.csv", export.chunks())10 .await?;1use laravel::http::client;2use laravel::storage;34let export = client::get("https://partner.example.com/exports/orders.csv")5 .stream()6 .await?;78storage::disk("s3")?9 .write_stream("exports/orders.csv", export.chunks())10 .await?;
To stream a file out of storage in chunks, call read_stream. Its stream field yields the file's bytes, which you can pipe directly into write_stream on another disk.
Copying and moving files
Use copy and move_to to copy or move files within a single disk, or copy_to_disk and move_to_disk to transfer files across disks (copy_to_disk_as and move_to_disk_as store the file at a different path on the destination disk):
1use laravel::storage;23storage::copy("reports/annual.pdf", "archive/annual.pdf").await?;45let local = storage::disk("local")?;6let s3 = storage::disk("s3")?;78local.copy_to_disk(&s3, "reports/annual.pdf").await?;910local.move_to_disk_as(&s3, "reports/annual.pdf", "archive/annual.pdf").await?;1use laravel::storage;23storage::copy("reports/annual.pdf", "archive/annual.pdf").await?;45let local = storage::disk("local")?;6let s3 = storage::disk("s3")?;78local.copy_to_disk(&s3, "reports/annual.pdf").await?;910local.move_to_disk_as(&s3, "reports/annual.pdf", "archive/annual.pdf").await?;
Moving a file across disks copies it first and deletes the original only if the copy succeeds.
File uploads
User uploads such as avatars and documents arrive as UploadedFile fields on a validated form. Call .store(directory) to save the file under a randomly generated filename with an extension derived from its contents. store returns the stored path so you can persist it in your database:
1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct UpdateAvatar {7 #[validate(required, image, max_kilobytes(2048))]8 avatar: UploadedFile,9}1011pub async fn update(Valid(form): Valid<UpdateAvatar>) -> laravel::Result<Redirect> {12 let path = form.avatar.store("avatars").disk("public").await?;1314 // Save the path on the user...1516 Ok(Redirect::back())17}1use laravel::http::UploadedFile;2use laravel::prelude::*;34#[laravel::input]5#[validate(authenticated)]6pub struct UpdateAvatar {7 #[validate(required, image, max_kilobytes(2048))]8 avatar: UploadedFile,9}1011pub async fn update(Valid(form): Valid<UpdateAvatar>) -> laravel::Result<Redirect> {12 let path = form.avatar.store("avatars").disk("public").await?;1314 // Save the path on the user...1516 Ok(Redirect::back())17}
Omitting .disk(..) writes to your default disk. To choose the filename yourself, use store_as. For example, this handler names each avatar after the user's ID:
1use laravel::prelude::*;23use crate::models::User;45pub async fn update(6 user: Authenticated<User>,7 Valid(form): Valid<UpdateAvatar>,8) -> laravel::Result<Redirect> {9 let extension = form.avatar.extension().unwrap_or("png");1011 form.avatar12 .store_as("avatars", format!("{}.{extension}", user.id))13 .disk("public")14 .await?;1516 Ok(Redirect::back())17}1use laravel::prelude::*;23use crate::models::User;45pub async fn update(6 user: Authenticated<User>,7 Valid(form): Valid<UpdateAvatar>,8) -> laravel::Result<Redirect> {9 let extension = form.avatar.extension().unwrap_or("png");1011 form.avatar12 .store_as("avatars", format!("{}.{extension}", user.id))13 .disk("public")14 .await?;1516 Ok(Redirect::back())17}
extension() inspects the file's contents rather than the client-supplied filename, so after the image validation rule passes, it is guaranteed to be a valid image extension such as png or jpg.
Never pass client_name to store_as, since users control that value and could overwrite another user's file. To learn more about inspecting uploaded files, check out the file uploads section of the requests guide.
Deleting files
Use storage::delete to remove a file. Deleting a path that does not exist succeeds without error:
1use laravel::storage;23storage::delete("avatars/1.png").await?;1use laravel::storage;23storage::delete("avatars/1.png").await?;
Directories
Use files to list files in a directory and all_files to include files in nested subdirectories. Similarly, directories and all_directories list subdirectories and nested subdirectories. Each returns a stream of paths that you can collect with try_collect:
1use laravel::storage;2use laravel::stream::TryStreamExt;34let reports: Vec<String> = storage::files("reports")?.try_collect().await?;1use laravel::storage;2use laravel::stream::TryStreamExt;34let reports: Vec<String> = storage::files("reports")?.try_collect().await?;
Use make_directory to create a directory along with any missing parent directories; if the directory already exists, it succeeds without error. Use delete_directory to delete a directory along with all of its contents:
1storage::make_directory("reports/2026").await?;23storage::delete_directory("reports/2025").await?;1storage::make_directory("reports/2026").await?;23storage::delete_directory("reports/2025").await?;
Testing
Call storage::fake at the start of a test to replace any disk (including s3) with an isolated, empty temporary directory for the duration of the test:
1use laravel::http::client::Attachment;2use laravel::model::create;3use laravel::storage;4use laravel::testing::prelude::*;56use app::models::User;78#[laravel::test]9async fn users_can_upload_an_avatar(app: Application) -> laravel::Result<()> {10 let disk = storage::fake("public")?;1112 let user = create!(User {13 name: "Taylor",15 password: "password",16 })17 .await?;1819 app.post("/avatar")20 .acting_as(&user)21 .attach("avatar", Attachment::from_path("tests/fixtures/avatar.png"))22 .await23 .assert_redirect();2425 disk.assert_exists(&format!("avatars/{}.png", user.id)).await;2627 Ok(())28}1use laravel::http::client::Attachment;2use laravel::model::create;3use laravel::storage;4use laravel::testing::prelude::*;56use app::models::User;78#[laravel::test]9async fn users_can_upload_an_avatar(app: Application) -> laravel::Result<()> {10 let disk = storage::fake("public")?;1112 let user = create!(User {13 name: "Taylor",15 password: "password",16 })17 .await?;1819 app.post("/avatar")20 .acting_as(&user)21 .attach("avatar", Attachment::from_path("tests/fixtures/avatar.png"))22 .await23 .assert_redirect();2425 disk.assert_exists(&format!("avatars/{}.png", user.id)).await;2627 Ok(())28}
The returned fake also provides assert_missing and assert_contents for verifying file absence or exact bytes. Each test's fake is isolated to its own application, so concurrent tests never share files. You can learn more about building test requests in the testing guide.