Upload Files to MySQL Database in Laravel Tutorial

By Hardik Savani April 16, 2024 Category : Laravel

Hi Guys,

In this tutorial, you will discover laravel save base64 image to database. We will look at an example of laravel save file to mysql database. This tutorial will give you a simple example of upload file to mysql database using laravel. This article will give you a simple example of laravel save base64 image to mysql database. Alright, let us dive into the details.

In this tutorial, we will create two routes one for the get method to render forms and another for the post method to upload file and store to mysql database code. we created a simple form with file input. So you have to simply select a file and then we will convert file to base64 string and store it into mysql database.

So you have to simply follow below steps to upload files to mysql database in laravel. you can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create files Table and Model

Here, we will create migration for files table. we will take name, mime and file column. we will add MEDIUMBLOB datatype for file column. so, let's create migration and run it.

php artisan create_files_table

database/migrations/migration_file.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\DB;

return new class extends Migration

{

/**

* Run the migrations.

*/

public function up(): void

{

Schema::create('files', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->string('mime');

$table->timestamps();

});

DB::statement("ALTER TABLE files ADD file MEDIUMBLOB");

}

/**

* Reverse the migrations.

*/

public function down(): void

{

Schema::dropIfExists('files');

}

};

Step 3: Create Controller

In this step, we will create a new FileController; in this file, we will add two method index() and store() for render view and store file logic.

Let's create FileController by following command:

php artisan make:controller FileController

next, let's update the following code to Controller File.

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\View\View;

use Illuminate\Http\RedirectResponse;

use App\Models\File;

class FileController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(): View

{

$files = File::latest()->get();

return view('fileUpload', compact('files'));

}

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function store(Request $request): RedirectResponse

{

$request->validate([

'file' => 'mimes:jpeg,bmp,png,pdf,jpg',

'name' => 'required|max:255',

]);

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

$path = $request->file('file')->getRealPath();

$ext = $request->file->extension();

$doc = file_get_contents($path);

$base64 = base64_encode($doc);

$mime = $request->file('file')->getClientMimeType();

File::create([

'name'=> $request->name .'.'.$ext,

'file' => $base64,

'mime'=> $mime,

]);

}

return back()

->with('success','You have successfully upload file.');

}

}

Step 4: Create and Add Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for render view and store file logic.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FileController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('file-upload', [FileController::class, 'index']);

Route::post('file-upload', [FileController::class, 'store'])->name('file.store');

Step 5: Create Blade File

At last step we need to create fileUpload.blade.php file and in this file we will create form with file input button. So copy bellow and put on that file.

resources/views/fileUpload.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel File Upload to MySQL Database Example - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

<div class="container">

<div class="panel panel-primary">

<div class="panel-heading">

<h2>Laravel File Upload to MySQL Database Example - ItSolutionStuff.com</h2>

</div>

<div class="panel-body">

@if ($message = Session::get('success'))

<div class="alert alert-success alert-block">

<strong>{{ $message }}</strong>

</div>

@endif

<div class="row">

@if ($files->count())

<h3>Files</h3>

<table class="table table-striped table-bordered table-hover">

<thead>

<tr>

<td>Name</td>

<td></td>

</tr>

</thead>

<tbody>

@foreach ($files as $file)

<tr>

<td>{{ $file->name }}</td>

<td><img src="data:{{ $file->mime }};base64,{{ $file->file }}" style="height: 100px; width: auto"></td>

</tr>

</tbody>

@endforeach

</table>

@endif

</div>

<h3>Upload File:</h3>

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

@csrf

<div class="mb-3">

<label class="form-label" for="inputFile">Name:</label>

<input

type="text"

name="name"

id="inputFile"

class="form-control @error('name') is-invalid @enderror">

@error('name')

<span class="text-danger">{{ $message }}</span>

@enderror

</div>

<div class="mb-3">

<label class="form-label" for="inputFile">File:</label>

<input

type="file"

name="file"

id="inputFile"

class="form-control @error('file') is-invalid @enderror">

@error('file')

<span class="text-danger">{{ $message }}</span>

@enderror

</div>

<div class="mb-3">

<button type="submit" class="btn btn-success">Upload</button>

</div>

</form>

</div>

</div>

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/file-upload

Database Output:

I hope it can help you...

Tags :
Shares