How to Upload Image in Laravel 8 using Summernote Editor

The extensive on Laravel  summernote editor image file upload; in this example, you will learn to add summernote editor in laravel app not-only but also ascertain how to upload image file through summernote editor in laravel using summernote editor lib and store the summernote editor’s content in the database.

The summernote is a profound and powerful JavaScript package that help you to build WYSIWYG editors online. You can download it directly or use CDN links to integrate it into the laravel application and we will show you how you can add an image in the summernote editor and then upload it to database in the laravel app.

How to Use Summernote Editor for Image Upload in Laravel

  • Step 1: Create New Laravel Project
  • Step 2: Put In 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 section explains how to use command and then install the new laravel app without getting into the needless process.

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

Don’t forget to get inside the app’s root:

cd JobBoard
Bash

Put In Database Details in ENV

This step explains how to upload the image file, and we will store the image into the database after uploading; for that we need to make the consensus between laravel and MYSQL db Consequently, open and update the .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
Bash

Manage Model and Migration

In this section, we will create a migration and model ideally, migration is the process of creating a new table inside the db. At the same time, the model is class which depicts the logical structure of a table.

Run suggested command to manifest a new migration and model.

php artisan make:model Employee -m
Bash

Open app/Models/Employee.php and then add the values in the newly generated models 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',
    ];
}
PHP

Open database/migrations/create_employees_table.php and then insert the table values inside 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');
    }
}
PHP

Next, open the terminal, type recommended command and then evoke the command to run the migration.

php artisan migrate
Bash

Construct Laravel Controller

Subsequently, we need to generate new fresh controller for adding associated logical request handling code for handling summernote editor file upload in single class.

php artisan make:controller EmployeeController
Bash

Furthermore you require to add code this 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);
    }
}
PHP

Fabricate New Routes

To make a HTTP req for adding summernote editor in same way to display the file 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']);
PHP

Set Up Blade View

You need to add the Bootstrap css and JavaScript in the same way Summer editor CSS , JavaScript CDN urls. We need to build the small form, add the text input field, text area. the text area will convert into the summernote file upload editor.

Let us conjugate entire code in resources/views/welcome.blade.php; this file formulates 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>
PHP

Start Laravel App

It is imperative to start laravel project, ensure that you have invoked the given below command from the command prompt.

php artisan serve
Bash

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

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

Conclusion

Summernote editor is the handy yet powerful tool based on JavaScript; it is not just an ordinary WYSIWYG Editor. Rather, it enhances user experience , helps users in many ways, especially when managing content from the editor is necessary. This gradual Laravel summernote editor image upload example consecutively explained every instruction, which helps build a summernote file upload functionality in the laravel application.

Post a Comment

Previous Post Next Post