File Storage
- Introduction
- Configuration
- Obtaining disk instances
- Retrieving files
- Storing files
- Deleting files
- Directories
- Testing
Introduction
Applications store all kinds of files, such as avatars that users upload, invoices you generate, and exports for a nightly report. The storage package gives you one API for files on your server's disk, in Laravel Cloud Object Storage, and in S3-compatible object storage, so the code that reads and writes a file stays the same whether the file lives on your server or in the cloud.
Configuration
Files live on named disks, and each disk is either a directory on your server or a bucket in S3-compatible storage. The FILESYSTEM_DISK environment variable names the default disk, which the storage package's functions use. Laravel defines three disks for you:
| Disk | Location | Access |
|---|---|---|
local |
storage/app/private (the default disk). |
Your handlers and temporary URLs. |
public |
storage/app/public. |
Anyone, from /storage. |
s3 |
The bucket that the AWS_* variables configure, once you set AWS_BUCKET. |
Whoever your bucket's policy allows. |
Most applications only need these disks. To add another disk, such as a directory for documents, add it to cfg.Filesystems.Disks in the configure function of your application's options, which Laravel runs for your application and its tests. A local disk's root is relative to your application's base path:
1// bootstrap/app.go2package bootstrap34import (5 laravel "go.laravel.com"6 "go.laravel.com/config"7)89func Options() laravel.Options {10 return laravel.Options{11 Configure: configure,12 // ...13 }14}1516func configure(cfg *config.Config, env *config.Env) {17 cfg.Filesystems.Disks["documents"] = config.LocalDisk{Root: "storage/app/documents"}18}1// bootstrap/app.go2package bootstrap34import (5 laravel "go.laravel.com"6 "go.laravel.com/config"7)89func Options() laravel.Options {10 return laravel.Options{11 Configure: configure,12 // ...13 }14}1516func configure(cfg *config.Config, env *config.Env) {17 cfg.Filesystems.Disks["documents"] = config.LocalDisk{Root: "storage/app/documents"}18}
The public disk
The public disk stores files that anyone may download, such as user avatars. Laravel serves its files at /storage, so a file stored at avatars/1.png is served at https://example.com/storage/avatars/1.png.
A local disk that you add isn't served over HTTP until you give it a Mount, the URL path that serves the disk's files. With only a mount, the disk's files download only through temporary URLs. Set Public to let anyone download them directly:
1cfg.Filesystems.Disks["images"] = config.LocalDisk{2 Root: "storage/app/images",3 Mount: "/images",4 Public: true,5}67cfg.Filesystems.Disks["documents"] = config.LocalDisk{8 Root: "storage/app/documents",9 Mount: "/documents",10}1cfg.Filesystems.Disks["images"] = config.LocalDisk{2 Root: "storage/app/images",3 Mount: "/images",4 Public: true,5}67cfg.Filesystems.Disks["documents"] = config.LocalDisk{8 Root: "storage/app/documents",9 Mount: "/documents",10}
With this configuration, anyone may download a file stored at banners/hero.png on the images disk from https://example.com/images/banners/hero.png, while files on the documents disk download from /documents only through temporary URLs.
If one of your application's routes matches the same path as a disk's mount, your route takes precedence.
Laravel Cloud Object Storage
When you deploy to Laravel Cloud, keep uploaded and generated files in Laravel Cloud Object Storage buckets rather than on the server's disk, because each deploy starts with a fresh disk and your instances don't share one. Laravel Cloud Object Storage works out of the box, with no AWS SDK to install.
When you attach a bucket to an environment in the Laravel Cloud dashboard, Laravel adds a disk for the bucket under the disk name you chose. That disk replaces any built-in disk with the same name, such as local or public, so your application may use local disks in development and Cloud buckets in production without changing your code. If you mark a bucket as the environment's default disk in the dashboard, the storage package's functions use that bucket.
A bucket's visibility applies to all of its files. Files in a public bucket have public URLs on the bucket's public domain, while files in a private bucket download only through temporary URLs, which last 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 reach a Laravel Cloud bucket from outside Laravel Cloud, such as during local development, add a config.CloudDisk in your configure function with the bucket's name, endpoint, and access keys from the dashboard. Leave out URL for a private bucket:
1cfg.Filesystems.Disks["avatars"] = config.CloudDisk{2 Bucket: "avatars",3 Endpoint: env.String("CLOUD_BUCKET_ENDPOINT", ""),4 URL: "https://avatars.laravel.cloud",5 Credentials: config.AWSCredentials{6 AccessKeyID: env.String("CLOUD_BUCKET_KEY", ""),7 SecretAccessKey: env.String("CLOUD_BUCKET_SECRET", ""),8 },9}1cfg.Filesystems.Disks["avatars"] = config.CloudDisk{2 Bucket: "avatars",3 Endpoint: env.String("CLOUD_BUCKET_ENDPOINT", ""),4 URL: "https://avatars.laravel.cloud",5 Credentials: config.AWSCredentials{6 AccessKeyID: env.String("CLOUD_BUCKET_KEY", ""),7 SecretAccessKey: env.String("CLOUD_BUCKET_SECRET", ""),8 },9}
S3-compatible disks
To store files in Amazon S3 or another S3-compatible object store, set the AWS_* variables in your .env file. Setting AWS_BUCKET adds the s3 disk, and Laravel signs its requests to S3 itself, so there's no AWS SDK to install. If you leave out the access key and secret, Laravel finds credentials the way the AWS command line tool does, such as from 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. For Cloudflare R2, also set AWS_DEFAULT_REGION to auto:
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 start of the disk's public file URLs, such as your CDN's domain. Your bucket's policy controls whether its files are publicly readable. Laravel never changes a file's permissions, so a public URL to a file in a private bucket doesn't expose the file.
To configure another S3 bucket, add a config.S3Disk in your configure function. You may also set Credentials, Endpoint, PathStyle, and URL to customize the disk:
1cfg.Filesystems.Disks["documents"] = config.S3Disk{2 Bucket: "acme-documents",3 Region: "eu-west-1",4 Endpoint: "https://objects.example.com",5 PathStyle: true,6 URL: "https://documents.example.com",7 Credentials: config.AWSCredentials{8 AccessKeyID: env.String("DOCS_AWS_ACCESS_KEY_ID", ""),9 SecretAccessKey: env.String("DOCS_AWS_SECRET_ACCESS_KEY", ""),10 },11}1cfg.Filesystems.Disks["documents"] = config.S3Disk{2 Bucket: "acme-documents",3 Region: "eu-west-1",4 Endpoint: "https://objects.example.com",5 PathStyle: true,6 URL: "https://documents.example.com",7 Credentials: config.AWSCredentials{8 AccessKeyID: env.String("DOCS_AWS_ACCESS_KEY_ID", ""),9 SecretAccessKey: env.String("DOCS_AWS_SECRET_ACCESS_KEY", ""),10 },11}
AWS credentials
On AWS, you'll usually give the server an IAM role rather than copying long-lived keys into .env. When a disk has no keys, Laravel looks for credentials in the AWS_* environment variables, then the profile that AWS_PROFILE names, then the role that EC2, ECS, or EKS gives the server, and refreshes a role's temporary credentials before they expire. Without AWS_DEFAULT_REGION, Laravel looks for the region in the same places, and uses us-east-1 when nothing sets one.
On your own machine, you may set AWS_PROFILE to work as a profile you already use with the AWS command line tool, including one you log in to with aws sso login:
1AWS_PROFILE=acme-staging2AWS_BUCKET=acme-staging-uploads1AWS_PROFILE=acme-staging2AWS_BUCKET=acme-staging-uploads
Read-through disks
When you move your files from one disk to another, such as from local storage to S3, a read-through disk lets your application stay online during the move. Reads check the primary disk first and fall back to the secondary disk when the primary doesn't have the file, while writes always go to the primary disk:
1cfg.Filesystems.Disks["uploads"] = config.ReadThroughDisk{Primary: "s3", Fallback: "local"}1cfg.Filesystems.Disks["uploads"] = config.ReadThroughDisk{Primary: "s3", Fallback: "local"}
By default, when a read finds a file on the fallback disk, Laravel copies the file to the primary disk so future reads find it there. If that copy fails, Laravel logs the failure and the read still succeeds, unless you set Promotion to config.PromoteRequired. To leave files on the fallback disk, set Promotion to config.PromoteNever.
Deleting a file removes it from both disks, so a stale copy can't resurface from the fallback.
Obtaining disk instances
The storage package's functions work on your default disk. Each one takes a context first, and in a handler you pass the request. For example, this handler writes a CSV report to the default disk:
1package reports23import (4 "go.laravel.com/storage"5 "go.laravel.com/web"6)78func Store(r *web.Request) *web.Response {9 err := storage.Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))10 if err != nil {11 return web.Fail(err)12 }1314 return web.Back()15}1package reports23import (4 "go.laravel.com/storage"5 "go.laravel.com/web"6)78func Store(r *web.Request) *web.Response {9 err := storage.Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))10 if err != nil {11 return web.Fail(err)12 }1314 return web.Back()15}
To target a specific disk, pass its name to storage.Use, which returns a disk with a method for each of the package's functions. A call panics when your configuration has no disk with that name:
1err := storage.Use("s3").Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))1err := storage.Use("s3").Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))
Storage functions work anywhere your application runs, including handlers, console commands, and queued jobs. Outside a handler, pass the ctx you received. Paths are relative to the disk's root, so reports/monthly.csv on the local disk maps to storage/app/private/reports/monthly.csv. A path that starts with / or contains a .. segment fails with an error that matches fs.ErrInvalid.
A few functions take a disk rather than a disk's name, such as web.DiskDownload. For those, storage.From(ctx) returns the default disk, and its Disk method returns another disk by name, as in storage.From(r).Disk("public").
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 with the Build method of storage.From(ctx):
1import (2 "go.laravel.com/config"3 "go.laravel.com/storage"4)56imports, err := storage.From(ctx).Build(config.LocalDisk{Root: "/var/imports"})7if err != nil {8 return err9}1011orders, err := imports.Get(ctx, "orders.csv")1import (2 "go.laravel.com/config"3 "go.laravel.com/storage"4)56imports, err := storage.From(ctx).Build(config.LocalDisk{Root: "/var/imports"})7if err != nil {8 return err9}1011orders, err := imports.Get(ctx, "orders.csv")
Laravel doesn't serve a built local disk, so it has no mount and can't generate URLs, though it can still send downloads. A built S3 or Laravel Cloud disk generates both public and temporary URLs as usual.
Retrieving files
Use storage.Get to read a file's bytes, or storage.JSON to decode a JSON file into the type you name in brackets, such as a struct of your own settings:
1import "go.laravel.com/storage"23type Settings struct {4 Theme string `json:"theme"`5 Notifications bool `json:"notifications"`6}78contents, err := storage.Get(r, "reports/monthly.csv")910settings, err := storage.JSON[Settings](r, "settings.json")1import "go.laravel.com/storage"23type Settings struct {4 Theme string `json:"theme"`5 Notifications bool `json:"notifications"`6}78contents, err := storage.Get(r, "reports/monthly.csv")910settings, err := storage.JSON[Settings](r, "settings.json")
Because Get and JSON read the whole file into memory, they refuse a file larger than 8 MiB with an error that matches storage.ErrTooLarge. For a larger file, raise the limit with GetWithLimit, or open the file with ReadStream and read it as you go. The *storage.File that ReadStream returns is an io.ReadSeekCloser, so you may pass it to anything that reads an io.Reader, such as csv.NewReader. Close the file when you're done:
1contents, err := storage.GetWithLimit(ctx, "exports/orders.csv", 32<<20)23file, err := storage.ReadStream(ctx, "exports/orders.csv")4if err != nil {5 return err6}7defer file.Close()89orders := csv.NewReader(file)1011// Read each order...1contents, err := storage.GetWithLimit(ctx, "exports/orders.csv", 32<<20)23file, err := storage.ReadStream(ctx, "exports/orders.csv")4if err != nil {5 return err6}7defer file.Close()89orders := csv.NewReader(file)1011// Read each order...
Check whether a file exists with storage.Exists or storage.Missing:
1exists, err := storage.Exists(r, "reports/monthly.csv")1exists, err := storage.Exists(r, "reports/monthly.csv")
Reading a missing file fails with an error that matches fs.ErrNotExist. Returning that error from a handler with web.Fail produces a 500 response, since a missing internal file usually means a bug. When the request names the file, answer with a 404 instead:
1package reports23import (4 "errors"5 "io/fs"6 "net/http"78 "go.laravel.com/storage"9 "go.laravel.com/web"10)1112func Show(r *web.Request) *web.Response {13 contents, err := storage.Get(r, "reports/"+r.PathValue("name"))14 if errors.Is(err, fs.ErrNotExist) {15 return web.Abort(http.StatusNotFound)16 }17 if err != nil {18 return web.Fail(err)19 }2021 return web.Text(string(contents))22}1package reports23import (4 "errors"5 "io/fs"6 "net/http"78 "go.laravel.com/storage"9 "go.laravel.com/web"10)1112func Show(r *web.Request) *web.Response {13 contents, err := storage.Get(r, "reports/"+r.PathValue("name"))14 if errors.Is(err, fs.ErrNotExist) {15 return web.Abort(http.StatusNotFound)16 }17 if err != nil {18 return web.Fail(err)19 }2021 return web.Text(string(contents))22}
Downloading files
Return web.DiskDownload from a handler to prompt the browser to save a file. The browser saves the file under the name you pass, or under the path's filename when you pass "". To display a file in the browser instead, such as a PDF or an image, return web.DiskFile. Both answer with a 404 when the file doesn't exist:
1package invoices23import (4 "go.laravel.com/storage"5 "go.laravel.com/web"6)78func Download(r *web.Request) *web.Response {9 // Verify that the user is authorized to view this invoice...1011 path := "invoices/" + r.PathValue("invoice") + ".pdf"1213 return web.DiskDownload(storage.From(r), path, "Invoice.pdf")14}1package invoices23import (4 "go.laravel.com/storage"5 "go.laravel.com/web"6)78func Download(r *web.Request) *web.Response {9 // Verify that the user is authorized to view this invoice...1011 path := "invoices/" + r.PathValue("invoice") + ".pdf"1213 return web.DiskDownload(storage.From(r), path, "Invoice.pdf")14}
Because downloads pass through your handler, you can authorize every request. Use web.DiskDownload 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 local disk with Public set, a public Laravel Cloud bucket, or an S3 disk:
1link, err := storage.Use("public").URL(r, "avatars/1.png")1link, err := storage.Use("public").URL(r, "avatars/1.png")
On the public disk, this returns https://example.com/storage/avatars/1.png. On a public Laravel Cloud bucket, it returns a URL on the bucket's public domain. On an S3 disk, it uses AWS_URL if you set it, or the bucket's own URL otherwise.
Temporary URLs
To grant time-limited access to a private file, generate a signed temporary URL:
1link, err := storage.TemporaryURL(r, "invoices/1.pdf", 5*time.Minute)1link, err := storage.TemporaryURL(r, "invoices/1.pdf", 5*time.Minute)
On a local disk, Laravel signs the URL with your application key and serves the file from the disk's mount. On S3 and Laravel Cloud, the signed URL sends the browser straight to your bucket.
You may also let browsers upload a file straight to a disk, which keeps large files such as videos from passing through your application on S3 or Laravel Cloud. TemporaryUploadURL returns the signed URL, along with the HTTP method and headers the browser must send:
1upload, err := storage.TemporaryUploadURL(r, "incoming/video.mp4", 5*time.Minute)2if err != nil {3 return web.Fail(err)4}56return web.JSON(map[string]any{7 "url": upload.URL,8 "method": upload.Method,9 "headers": upload.Header,10})1upload, err := storage.TemporaryUploadURL(r, "incoming/video.mp4", 5*time.Minute)2if err != nil {3 return web.Fail(err)4}56return web.JSON(map[string]any{7 "url": upload.URL,8 "method": upload.Method,9 "headers": upload.Header,10})
File metadata
Use Size, LastModified, and MimeType to read one of a file's details, or a disk's Metadata method to read all three in one call. Metadata returns a storage.Metadata with Size, ContentType, and LastModified fields:
1size, err := storage.Size(r, "reports/monthly.csv")2modified, err := storage.LastModified(r, "reports/monthly.csv")3mimeType, err := storage.MimeType(r, "reports/monthly.csv")45metadata, err := storage.From(r).Metadata(r, "reports/monthly.csv")1size, err := storage.Size(r, "reports/monthly.csv")2modified, err := storage.LastModified(r, "reports/monthly.csv")3mimeType, err := storage.MimeType(r, "reports/monthly.csv")45metadata, err := storage.From(r).Metadata(r, "reports/monthly.csv")
Because the MIME type comes from the file's name or from the storage service rather than from the file's bytes, don't rely on MimeType for security checks.
Storing files
Use storage.Put to write a file, replacing any file already at that path. For example, this stores a CSV report and an avatar fetched with the HTTP client, whose response's Body holds the bytes:
1import (2 "go.laravel.com/httpclient"3 "go.laravel.com/storage"4)56err := storage.Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))78avatar, err := httpclient.EnsureSuccessful().Get(r, "https://example.com/avatars/taylor.png")9if err != nil {10 return web.Fail(err)11}1213err = storage.Put(r, "avatars/1.png", avatar.Body)1import (2 "go.laravel.com/httpclient"3 "go.laravel.com/storage"4)56err := storage.Put(r, "reports/monthly.csv", []byte("name,total\nTaylor,42\n"))78avatar, err := httpclient.EnsureSuccessful().Get(r, "https://example.com/avatars/taylor.png")9if err != nil {10 return web.Fail(err)11}1213err = storage.Put(r, "avatars/1.png", avatar.Body)
Streaming large files
Put holds the whole file in memory. For large files such as videos or database exports, use WriteStream, which writes the contents of an io.Reader to storage as they arrive. For example, this function from an import command streams a partner's export to S3:
1package commands23import (4 "context"5 "net/http"67 "go.laravel.com/httpclient"8 "go.laravel.com/storage"9)1011func importOrders(ctx context.Context) error {12 export, err := httpclient.EnsureSuccessful().13 Stream(ctx, http.MethodGet, "https://partner.example.com/exports/orders.csv")14 if err != nil {15 return err16 }17 defer export.Body.Close()1819 return storage.Use("s3").WriteStream(ctx, "exports/orders.csv", export.Body)20}1package commands23import (4 "context"5 "net/http"67 "go.laravel.com/httpclient"8 "go.laravel.com/storage"9)1011func importOrders(ctx context.Context) error {12 export, err := httpclient.EnsureSuccessful().13 Stream(ctx, http.MethodGet, "https://partner.example.com/exports/orders.csv")14 if err != nil {15 return err16 }17 defer export.Body.Close()1819 return storage.Use("s3").WriteStream(ctx, "exports/orders.csv", export.Body)20}
To stream a file out of storage, open it with ReadStream. The file it returns is an io.Reader, so you may pass it straight to WriteStream on another disk.
Copying and moving files
Use Copy and Move to copy or move a file within one disk, or CopyToDisk and MoveToDisk to transfer a file to another disk. The last argument of CopyToDisk and MoveToDisk is the path on the destination disk, or "" to keep the same path:
1err := storage.Copy(r, "reports/annual.pdf", "archive/annual.pdf")23local := storage.Use("local")4s3 := storage.Use("s3")56err = local.CopyToDisk(r, "reports/annual.pdf", s3, "")78err = local.MoveToDisk(r, "reports/annual.pdf", s3, "archive/annual.pdf")1err := storage.Copy(r, "reports/annual.pdf", "archive/annual.pdf")23local := storage.Use("local")4s3 := storage.Use("s3")56err = local.CopyToDisk(r, "reports/annual.pdf", s3, "")78err = local.MoveToDisk(r, "reports/annual.pdf", s3, "archive/annual.pdf")
Moving a file to another disk copies it first and deletes the original only if the copy succeeds.
File uploads
User uploads such as avatars and documents arrive as *web.Upload fields on a validated struct. Call Store with a disk and a directory to save the file under a randomly generated name, with an extension that matches its contents. Store returns the stored path so you can save it in your database:
1package avatars23import (4 "go.laravel.com/storage"5 "go.laravel.com/validation"6 "go.laravel.com/validation/rule"7 "go.laravel.com/web"8)910type UpdateAvatar struct {11 Avatar *web.Upload `json:"avatar"`12}1314func (f *UpdateAvatar) Rules() validation.Rules {15 return validation.For(f,16 rule.Field(&f.Avatar, rule.Required, rule.Image, rule.Max(2048)),17 )18}1920func Update(r *web.Request) *web.Response {21 form, err := r.Validate[UpdateAvatar]()22 if err != nil {23 return web.Fail(err)24 }2526 path, err := form.Avatar.Store(r, storage.Use("public"), "avatars")27 if err != nil {28 return web.Fail(err)29 }3031 // Save the path on the user...3233 return web.Back()34}1package avatars23import (4 "go.laravel.com/storage"5 "go.laravel.com/validation"6 "go.laravel.com/validation/rule"7 "go.laravel.com/web"8)910type UpdateAvatar struct {11 Avatar *web.Upload `json:"avatar"`12}1314func (f *UpdateAvatar) Rules() validation.Rules {15 return validation.For(f,16 rule.Field(&f.Avatar, rule.Required, rule.Image, rule.Max(2048)),17 )18}1920func Update(r *web.Request) *web.Response {21 form, err := r.Validate[UpdateAvatar]()22 if err != nil {23 return web.Fail(err)24 }2526 path, err := form.Avatar.Store(r, storage.Use("public"), "avatars")27 if err != nil {28 return web.Fail(err)29 }3031 // Save the path on the user...3233 return web.Back()34}
To store the file on the default disk, pass storage.From(r). To choose the filename yourself, use StoreAs. For example, this handler, on a route that requires a logged-in user, names each avatar after the user's ID:
1import (2 "fmt"34 "go.laravel.com/storage"5 "go.laravel.com/web"67 "app/models"8)910func Update(r *web.Request) *web.Response {11 form, err := r.Validate[UpdateAvatar]()12 if err != nil {13 return web.Fail(err)14 }1516 user := r.User[models.User]()17 name := fmt.Sprintf("%d.%s", user.ID, form.Avatar.Extension())1819 if _, err := form.Avatar.StoreAs(r, storage.Use("public"), "avatars", name); err != nil {20 return web.Fail(err)21 }2223 return web.Back()24}1import (2 "fmt"34 "go.laravel.com/storage"5 "go.laravel.com/web"67 "app/models"8)910func Update(r *web.Request) *web.Response {11 form, err := r.Validate[UpdateAvatar]()12 if err != nil {13 return web.Fail(err)14 }1516 user := r.User[models.User]()17 name := fmt.Sprintf("%d.%s", user.ID, form.Avatar.Extension())1819 if _, err := form.Avatar.StoreAs(r, storage.Use("public"), "avatars", name); err != nil {20 return web.Fail(err)21 }2223 return web.Back()24}
Extension inspects the file's bytes rather than the name the client sent, so once the Image rule passes, it's always an image extension such as png or jpg.
Never pass the upload's Name to StoreAs, since users control that value and could overwrite another user's file. To learn more about inspecting uploaded files, check out the requests guide's section on files.
Deleting files
Use storage.Delete to remove a file. Deleting a path that doesn't exist succeeds without error:
1err := storage.Delete(r, "avatars/1.png")1err := storage.Delete(r, "avatars/1.png")
Directories
Use Files to list the files in a directory, and AllFiles to include the files in nested subdirectories. Similarly, Directories and AllDirectories list subdirectories and nested subdirectories. Each returns an iterator of paths and errors that you range over:
1for path, err := range storage.Files(r, "reports") {2 if err != nil {3 return web.Fail(err)4 }56 // Use the path...7}1for path, err := range storage.Files(r, "reports") {2 if err != nil {3 return web.Fail(err)4 }56 // Use the path...7}
Use MakeDirectory to create a directory along with any missing parent directories, and DirectoryExists to check whether a directory is there. Use DeleteDirectory to delete a directory along with all of its contents:
1err := storage.MakeDirectory(r, "reports/2026")23exists, err := storage.DirectoryExists(r, "reports/2026")45err = storage.DeleteDirectory(r, "reports/2025")1err := storage.MakeDirectory(r, "reports/2026")23exists, err := storage.DirectoryExists(r, "reports/2026")45err = storage.DeleteDirectory(r, "reports/2025")
Testing
Pass laraveltest.FakeDisk the disks to fake when you build a test's client, and Laravel replaces each one, including s3, with an isolated, empty temporary directory for the duration of the test. laraveltest.FakeDisk() without names fakes the default disk. Then client.Disk returns the disk with assertions about its files:
1package feature_test23import (4 "fmt"5 "os"6 "testing"78 "go.laravel.com/laraveltest"9 "go.laravel.com/webtest"1011 "app/database/factories"12 "app/tests"13)1415func TestUsersCanUploadAnAvatar(t *testing.T) {16 client := tests.New(t, laraveltest.FakeDisk("public"))17 user := client.Create(factories.User)1819 avatar, err := os.ReadFile("testdata/avatar.png")20 if err != nil {21 t.Fatal(err)22 }2324 client.ActingAs(&user).Upload("/avatar", nil, webtest.File{25 Field: "avatar",26 Name: "avatar.png",27 Content: avatar,28 })2930 client.Disk("public").AssertExists(fmt.Sprintf("avatars/%d.png", user.ID))31}1package feature_test23import (4 "fmt"5 "os"6 "testing"78 "go.laravel.com/laraveltest"9 "go.laravel.com/webtest"1011 "app/database/factories"12 "app/tests"13)1415func TestUsersCanUploadAnAvatar(t *testing.T) {16 client := tests.New(t, laraveltest.FakeDisk("public"))17 user := client.Create(factories.User)1819 avatar, err := os.ReadFile("testdata/avatar.png")20 if err != nil {21 t.Fatal(err)22 }2324 client.ActingAs(&user).Upload("/avatar", nil, webtest.File{25 Field: "avatar",26 Name: "avatar.png",27 Content: avatar,28 })2930 client.Disk("public").AssertExists(fmt.Sprintf("avatars/%d.png", user.ID))31}
The faked disk also provides AssertMissing and AssertContents for checking that a file is absent or has exact contents. A faked disk keeps its mount, so its URLs still work, and a faked S3 disk serves its files at /<name>. Each test's fake is a directory of its own, so tests that run at the same time never share files. To learn more about sending files in tests, check out the testing guide's section on uploading files.