How to Upload Image using Summernote Editor in Laravel

Laravel Summernote Image Upload Example; In this tutorial, you will understand how to upload image using summernote editor in laravel public storage folder. Summernote editor store the images along with summernote editor’s content in the database easily.

The summernote is a profound and powerful JavaScript package that helps you build WYSIWYG editors online. Let’s see the below example to upload images/files using summernote in laravel application.

How to Use Summernote Editor for Image Upload in Laravel

Step 1: Install Laravel App
Step 2: Connect Database to App
Step 3: Manage Model and Migration
Step 4: Create Controller
Step 5: Add Routes
Step 6: Create Blade Files
Step 7: Start Laravel App

Install Laravel App

First run the following command in terminal to install laravel fresh app for laravel summernote image upload funcationality.

composer create-project laravel/laravel laravel-app

Go inside the app

cd laravel-app

Connect App to Database

Open the .env file and add your database credentials such as database name, username equally important password:

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

Generate Model and Migration

Now generate model and migration file just adding the below command in your terminal which is generate a model file and migration which will show your database table after running the migration command.

php artisan make:model Post -m

Open app/Models/Post.php and 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 Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'description', 'image'
    ];
}

Open database/migrations/create_posts_table.php and insert the table values inside the file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

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

php artisan migrate

Create Controller

Now you need to create a controller just adding the below command and generate a new resource controller PostController.

php artisan make:controller PostController

Next, in this file we write image upload code, image will upload on “uploads” folder in public directory. So, open app/Http/Controllers/PostController.php file and update the below code on it;

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {

        return view('posts');
    }

    public function store(Request $request)
    {
        $request->validate($request, [
             'title' => 'required',
             'description' => 'required'
        ]);

       $content = $request->input('description');
       $dom = new \DomDocument();
       $dom->loadHtml($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
       $imageFile = $dom->getElementsByTagName('img');

       foreach($imageFile as $item => $image){
           $data = $image->getAttribute('src');
           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);
           $imgeData = base64_decode($data);
           $image_name= "/uploads/" . time().$item.'.png';
           $path = public_path() . $image_name;
           file_put_contents($path, $imgeData);

           $image->removeAttribute('src');
           $image->setAttribute('src', $image_name);
        }

       $content = $dom->saveHTML();
       $post = Post::create([
            'title' => $request->title,
            'body' => $content
       ]);

       dd($post->toArray());
    }
}

Create Routes

In laravel 9 route section have some change here you need to use your controller then initialize the controller class. Open your “routes/web.php” file and your routes same as below.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('posts', [PostController::class, 'index'])->name('posts.index');
Route::post('posts', [PostController::class, 'store'])->name('posts.store');

Create Blade File

Now create a new blade file named as resources\views\posts.blade.php and update the below code on it.

resources\views\posts.blade.php

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Upload Image using Summernote Editor</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-bs5.min.css" />
</head>

<body>
    <div class="container mt-4">
        <h3 class="text-center">How to Upload Image using Summernote Editor in Laravel</h3>
        <form method="post" action="{{ route('posts.store') }}" enctype="multipart/form-data" class="mt-5">
            @csrf
            <div class="form-group">
                <label><strong>Title:</strong></label>
                <input type="text" name="title" class="form-control" />
            </div>
            <div class="form-group my-3">
                <label><strong>Description:</strong></label>
                <textarea id="summernote" name="description"></textarea>
            </div>
            <div class="form-group text-center">
                <button type="submit" class="btn btn-success 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://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.20/summernote-bs5.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#summernote').summernote({
                height: 300,
            });
        });
    </script>

</body>
</html>

Start Laravel App

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/posts

I hope you enjoy with this example…

Leave a Comment