How to Upload Image in Laravel 9 using Summernote Editor

This is an extensive guide on Laravel Summernote editor image file upload feature. In this tutorial, let’s learn how to add Summernote editor in your Laravel application.

We will discover how to upload image file through Summernote editor in Laravel using the Summernote editor library and save the Summernote editor’s content in our database.

Summernote is a profound and impactful JavaScript package that helps you build WYSIWYG editors online.

You may download it directly or use CDN links to integrate it in your Laravel application. We will now show you how to add an image file in the Summernote editor and upload it to the database in the Laravel app.

Summernote Editor for Image Upload – Laravel 9

  • Step 1: Create New Laravel Project
  • Step 2: Add Database Details in ENV
  • Step 3: Manage Model and Migration
  • Step 4: Construct Laravel Controller
  • Step 5: Fabricate New Routes
  • Step 6: Set Up Blade View
  • Step 7: Start Laravel App

Create New Laravel Project

The first step, you need to create a fresh Laravel project with the command below.

composer create-project --prefer-dist laravel/laravel JobBoard

Get inside your app’s root.

cd JobBoard

Add Database Details in ENV

Let’s set up the database credentials where we will save our image URL after uploading. We will make a connection between our Laravel application and MySQL database. Thereby, adding the following details in our .env configuration file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

In case you are using the MAMP local server in macOS, ensure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Model and Migration

In this section, we will create a Migration file and Model class. Migration is the process to create a new database table. The model is a class which shows the logical structure of the table.

Run the command given below to create a new migration and model.

php artisan make:model Employee -m

Open app/Models/Employee.php and add values given below in your newly generated model file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'name',
        'content',
    ];
}

Open your database/migrations/create_employees_table.php file and insert the table values in the file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->longText('content');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Finally, open your terminal, and type the command below to run the migration.

php artisan migrate

Construct Laravel Controller

Next, we need to create a new controller to add the associated logical request to add code for handling the Summernote editor file upload in a single class.

php artisan make:controller EmployeeController

Furthermore, we need to add code in app/Http/Controllers/EmployeeController.php file.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
    public function index()
    {
        return view('welcome');
    }
 
    public function fileUpload(Request $request)
    {
        $this->validate($request, [
             'name' => 'required',
             'content' => 'required'
        ]);
 
       $content = $request->content;
       $dom = new \DomDocument();
       $dom->loadHtml($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
       $imageFile = $dom->getElementsByTagName('imageFile');
 
       foreach($imageFile as $item => $image){
           $data = $img->getAttribute('src');
           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);
           $imgeData = base64_decode($data);
           $image_name= "/upload/" . time().$item.'.png';
           $path = public_path() . $image_name;
           file_put_contents($path, $imgeData);
           
           $image->removeAttribute('src');
           $image->setAttribute('src', $image_name);
        }
 
       $content = $dom->saveHTML();
       $fileUpload = new Employee;
       $fileUpload->name = $request->name;
       $fileUpload->content = $content;
       $fileUpload->save();
 
       dd($content);
    }
}

Fabricate New Routes

To make the HTTP request for adding Summernote editor, in the same way, to display the file upload in view, we need to create the routes, so add the below code in the routes/web.php file.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('/summernote-editor-upload', [EmployeeController::class, 'index']);
Route::post('file-upload', [EmployeeController::class, 'fileUpload']);

Set Blade View

We need to add Bootstrap CSS, JavaScript in similar way Summer editor CSS and JavaScript CDN URLs. We will create a small form, and add the text input and text area fields, where the text area will convert into a Summernote file upload editor.

Let us adjoin the entire code in resources/views/welcome.blade.php, this file creates the whole view of Laravel.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 8 Summernote Editor Image Upload Demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <form method="post" action="{{ url('file-upload') }}" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
                <label>Name</label>
                <input type="text" name="name" class="form-control" />
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea id="summernote" name="content"></textarea>
            </div>
            <div class="form-group text-center">
                <button type="submit" class="btn btn-danger btn-block">Publish</button>
            </div>
        </form>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#summernote').summernote({
                height: 450,
            });
        });
    </script>
</body>
</html>

Start Laravel App

It is essential to start the Laravel project, make sure you have passed the given below command from your command prompt or terminal.

php artisan serve

Type the suggested URL on the browser’s address bar to see the app in the action.

http://127.0.0.1:8000/summernote-file-upload

Conclusion

Summernote editor is a handy yet impactful tool based on JavaScript, it is not just an ordinary WYSIWYG Editor.

Moreover, it enhances user experience and helps users in many different ways, specifically when we manage content from the editor.

This tutorial on Laravel Summernote editor image upload explains all required use cases, this helps build the Summernote file upload functionality in your Laravel application.

Leave a Comment