How to upload a file in laravel?

Member

by jerad , in category: PHP Frameworks , 4 months ago

How to upload a file in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 20 days ago

@jerad 

To upload a file in Laravel, you can follow these steps:

  1. Create a form in your view file to allow users to select a file to upload:
1
2
3
4
5
<form action="/upload" method="post" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Upload File</button>
</form>


  1. Create a route in your routes file to handle the file upload request:
1
Route::post('/upload', 'FileController@upload');


  1. Create a controller to handle the file upload logic. Create a new controller file using artisan command:
1
php artisan make:controller FileController


Then, add the following code to the controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        $file = $request->file('file');
        $fileName = $file->getClientOriginalName();
        $file->move(public_path('uploads'), $fileName);

        return 'File uploaded successfully!';
    }
}


  1. Make sure to create a folder named 'uploads' in your public directory to store the uploaded files.
  2. That's it! Now, when a user selects a file and submits the form, the file will be uploaded to the 'uploads' folder in the public directory.


Please note that you may need to add validation and error handling to the above code to make it more robust.