Upload Files to MySQL Database in Laravel Tutorial
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Get File Mime Type from Storage Example
- How to Migrate SQL File in Laravel Migration?
- Laravel Import Large CSV File Using Queue Example
- How to Read Content from PDF File in Laravel?
- Laravel 10 Import Large CSV File into Database Example
- How to Create Zip File and Download in Laravel 10?
- Laravel Livewire File Upload Tutorial
- How to Create Custom Route File in Laravel?
- Laravel Vue JS File Upload Example
- Laravel Validation for Multiple Files in Array Example
- Laravel 11 Merge Multiple PDF Files Example
- Laravel Vue JS File Upload Using Vue-dropzone Example
- Laravel 11 File Upload with Progress Bar Example
- Laravel - How to Convert File(image, audio, video) Extension using CloudConvert?