How to upload and Download PDF in Laravel

How to upload and Download PDF in Laravel

In this article, we will see how to upload and download PDFs in Laravel step by step. File uploading and downloading is the main part of every website. After learning this article you will be able to make a system where users can upload and download files like PDF, Doc file, and Docx. We will also see validation rules for files like we will upload only required files and other files will get an error.

Step 1: Create a fresh project

Run the given command to create a Laravel fresh project.

Composer create-project Laravel/Laravel DocUpload

 

Step:2 Create Migration, Model, and Controller

Run the given command to create a Model, migration, and controller.

Php artisan make:model Document -mc

After that open your .env file and connect with the database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=docupload
DB_USERNAME=root
DB_PASSWORD=

 

Step: 3 Migration Update

Open your migration file and update it with the given code.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->string('file_name');
            $table->string('original_name');
            $table->timestamps();
        });
    }
    public function down(): void
    {
        Schema::dropIfExists('documents');
    }
};

Step: 4 Update Controller

Open your controller and update it with the given code.

<?php
namespace App\Http\Controllers;
use App\Models\Document;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
//views record function
public function index(){
    $doc = Document::orderBy('id','DESC')->get();
    return view('welcome',['docs'=>$doc]);
}


//upload function
public function upload(Request $request)

{
    $request->validate([
        'document' => 'required|mimes:pdf,doc,docx',
    ]);
    $file = $request->file('document');
    $originalName = $file->getClientOriginalName();
    $fileName = time() . '_' . $file->getClientOriginalName();
    $file->storeAs('documents', $fileName, 'public');

    $doc = new Document;
    $doc->file_name = $fileName;
    $doc->original_name = $originalName;
    $doc->save();
    return redirect()->back()->with('success', 'Document uploaded successfully.');
}

//download function
public function download($id)
{
    $document = Document::find($id);
    $filePath = storage_path("app/public/documents/{$document->file_name}");
    return response()->download($filePath, $document->original_name);
}
}

 

Step: 5 View File update

Open your view file welcome.blade.php and update with given code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Upload and Download Documents</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="row pt-5">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-head bg-warning">
                        <h2 class="pt-2 pb-2 text-center text-light">Upload and Download Documents</h2>
                    </div>
                    <div class="card-body">
                        @if ($errors->any())
                        <div class="alert alert-danger">
                            <ul>
                                @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                        @endif

                        @if (session('success'))
                        <div class="alert alert-success">
                            {{ session('success') }}
                        </div>
                        @endif

                        <form action="{{ route('upload') }}" method="post" enctype="multipart/form-data" class="form">
                            @csrf
                            <div class="form-group">
                                <input type="file" name="document" id="" class="form-control">
                            </div>
                            <div class="form-group pt-3">
                                <input type="submit" value="Save File" class="btn-primary btn-sm">
                            </div>
                        </form>

                        <h2 class="pt-1 pb-1 mt-3 bg-warning text-light text-center curved">List of Documents</h2>

                        <table class="table">
                            <thead>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Download</th>
                            </thead>
                            <tbody>
                                @foreach($docs as $mydoc)
                                <tr>
                                    <td>{{ $mydoc->id }}</td>
                                    <td>{{ $mydoc->original_name }}</td>
                                    <td><a href="{{ route('download', $mydoc->id) }}"
                                            class="btn btn-info btn-sm">Download File</a></td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

 

Step: 6 Routes creating

The last step is to create routes, open your route file web.php, and update with the given code.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DocumentController;

Route::get('/', [DocumentController::class, 'index']);
Route::post('/upload', [DocumentController::class, 'upload'])->name('upload');
Route::get('/download/{id}', [DocumentController::class, 'download'])->name('download');

 

In the next run the command to make migrations

Php artisan migrate

Everything is done just run the given command to start the server.

Php artisan serve

http://localhost:8000/

 

 

Comments

No Comment posted Yet!

Leave a Reply

OK! You can skip this field.