Upload file in Laravel

To upload files in Laravel, you need to follow these steps:


Step 1: Set Up a Form

Create a form in your view (Blade template) that allows users to select and upload a file. Use the HTML `<form>` tag with the `enctype` attribute set to `"multipart/form-data"` to enable file uploads:


<form action="{{ route('file.upload') }}" method="POST" enctype="multipart/form-data">

    @csrf

    <input type="file" name="file">

    <button type="submit">Upload</button>

</form>


Step 2: Define the Upload Route

Create a route that will handle the file upload request. Open the `routes/web.php` file and add the following route:


Route::post('/upload', 'FileController@upload')->name('file.upload');


Step 3: Create a Controller

Generate a controller to handle the file upload logic. Run the following command in your terminal:


php artisan make:controller FileController


Step 4: Implement the Upload Method

Open the `FileController.php` and implement the `upload` method:


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;


class FileController extends Controller

{

    public function upload(Request $request)

    {

        $request->validate([

            'file' => 'required|mimes:jpeg,png,pdf|max:2048', // Define allowed file types and maximum size

        ]);


        if ($request->file('file')->isValid()) {

            $path = $request->file('file')->store('uploads', 'public'); // Store the uploaded file in the 'public' disk under the 'uploads' directory


            // You can also save the file path to the database or perform other actions here


            return "File uploaded successfully!";

        }


        return "File upload failed.";

    }

}


In this example, the uploaded file is stored in the `public` disk under the `uploads` directory. Adjust the path and storage disk according to your requirements.


Step 5: Handle the Uploaded File

The uploaded file will be available in the `store` method's return value, which is the file path relative to the disk. You can use this path to display the uploaded file or perform any other actions as needed.


That's it! Users can now use the form to select and upload files, and the Laravel application will handle the file upload and storage.