How to upload file in Laravel


To upload a file in Laravel, you can use the Illuminate\Http\Request class’s file method to retrieve an instance of Illuminate\Http\UploadedFile representing the uploaded file, and then use the store method of the Illuminate\Http\UploadedFile class to store the file on the server.

Here is an example of how you can write a code to handle a file upload in a Laravel application:


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
    public function upload(Request $request)
        // Validate the request data
            'file' => 'required|file|max:1024',

        // Get an instance of the uploaded file
        $file = $request->file('file');

        // Generate a new file name
        $fileName = time() . '.' . $file->getClientOriginalExtension();

        // Store the file on the server
        $file->storeAs('public/files', $fileName);

        // Redirect the user back with a success message
        return redirect()->back()->with('success', 'File uploaded successfully');

In this example, the file is stored in the public/files directory on the server. You can customize this location by changing the first argument of the storeAs method.

You can also use the store method to store the file in a specific storage disk. For example, you can use the store method like this:

$file->store('public/files', ['disk' => 's3']);

This will store the file in the public/files directory on the Amazon S3 storage disk. You will need to configure your S3 credentials in the config/filesystems.php configuration file for this to work.

I hope this helps! Let me know if you have any questions.

Read More Articles


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.