How to upload a pdf document in laravel?

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

How to upload a pdf document in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 4 months ago

@dalton_moen 

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

  1. Create a form in your view file where users can select and upload a PDF document. Here's an example of a basic form:
1
2
3
4
5
<form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="pdf_document">
    <button type="submit">Upload PDF</button>
</form>


  1. Set up a route in your web.php file to handle the file upload:
1
Route::post('/upload', 'UploadController@upload')->name('upload');


  1. Create a controller to handle the file upload. Run the following command in your terminal to generate a new controller:
1
php artisan make:controller UploadController


Then, in the UploadController.php file, add the following code to handle the file upload:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public function upload(Request $request)
{
    $request->validate([
        'pdf_document' => 'required|mimes:pdf|max:2048',
    ]);

    $pdfDocument = $request->file('pdf_document');
    $pdfDocument->move(public_path('uploads'), $pdfDocument->getClientOriginalName());

    return redirect()->back()->with('success', 'PDF document has been uploaded successfully.');
}


  1. Create a new folder called "uploads" in the public directory of your Laravel project. This is where the uploaded PDF documents will be stored.
  2. That's it! Users can now upload PDF documents through the form on your website. The uploaded PDF documents will be stored in the "uploads" directory in the public folder.


Remember to handle errors and validations properly in your code to ensure a secure and smooth upload process.