In some applications, there might be a requirement to transfer files between the client and server. Laravel allows clients to send files to the server. Currently, Laravel supports only two storage drivers. Local storage, which uses the Storage directory in the application or Amazon S3.
Various operations can be performed on transferred files. When a file is uploaded, the server can validate it and change its name. Clients can download or preview files from the server if its properties allow doing that.
File operations
Laravel allows you to perform some basic operations on files. Create them on the server, read them, update them by replacing them, or, in the case of text files, append some additional data, and even delete them if it’s necessary
//Store file on server in avatars directory Storage::put('avatars', $file); //Store file on server in avatars directory as avatar.jpg Storage::putFileAs('avatars', $file, 'avatar.jpg'); //Copy image Storage::copy('avatars/avatar.jpg', 'avatars/avatar-copy.jpg'); //Move file to different directory and rename it Storage::move('avatars/avatar.jpg', 'thumbnails/thumbnail.jpg'); //Change visibility of file Storage::setVisibility('thumbnails/thumbnail.jpg', 'public'); //Send file to client Storage::download('thumbnails/thumbnail.jpg'); //Delete file from server Storage::delete('thumbnails/thumbnail.jpg');
File validations
File validations allow the server to check file type, extension, size and in case of images their resolution.
public function rules(): array { return [ 'file' => [ File::image() ->min(1024) ->max(5 * 1024) ->dimensions( Rule::dimensions() ->maxWidth(1920) ->maxHeight(1080) ), ] ]; }
File testing
Additional Storage Facade provides a function to create fake storage for testing purposes, like working on fake files and disks.
public function test_document_upload(): void { Storage::fake('local'); $response = $this->postJson('/documents', [ 'document' => UploadedFile::fake()->create( 'boxing_instruction.pdf', 100, 'application/pdf' ) ]); $response->assertCreated(); }