Laravel 11 Summernote Image Upload Example

Websolutionstuff | May-17-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to upload images in the Summernote text editor in laravel 11. Summernote is a WYSIWYG (What You See Is What You Get) editor that allows users to create rich text editors for web pages.

You can integrate any 3rd parties available in Django, rails, angular, and so on. Summernote is a JavaScript library that helps you create WYSIWYG editors online.

Laravel 11 Summernote Image Upload Example

laravel 11 summernote image upload example

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the composer command.

composer create-project laravel/laravel example-app

 

Step 2: Create Model and Migration

Then, we'll create migration and model using the following command.

php artisan make:migration create_posts_table

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

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

Then, migrate the table into the database using the following command.

php artisan migrate

app/Models/Post.php

<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
   
class Post extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body'
    ];
  
    /**
     * Get the user's first name.
     */
    protected function body(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => $this->makeBodyContent($value),
        );
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function makeBodyContent($content)
    {
        $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);
        }
       
        return $dom->saveHTML();
    }
}

 

Step 3: Define Routes

Next, we'll define the route into the web.php file

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;

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

 

Step 4: Create Controller

Then, we'll create a controller using the following command.

app/Http/Controllers/PostController.php

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
     
class PostController extends Controller
{
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create(): View
    {
        return view('posts-create');
    }
        
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request): RedirectResponse
    {
        $this->validate($request, [
             'title' => 'required',
             'body' => 'required'
        ]);
   
        $post = Post::create([
            'title' => $request->title,
            'body' => $request->body
        ]);
   
        return back()->with('success','Post created successfully.');
    }
}
 
Step 5: Create Blade File

Then, we'll create a post-create.blade.php file. add summernote text editor in that file.

resources/views/posts-create.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 11 Summernote Image Upload Example - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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">
    <div class="card mt-5">
        <h3 class="card-header p-3">Laravel 11 Summernote Image Upload Example - Techsolutionstuff</h3>
        <div class="card-body"> 
            <form method="post" action="{{ route('posts.store') }}" enctype="multipart/form-data">
                @csrf
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" name="title" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="summernote" name="body"></textarea>
                </div>
                <div class="form-group mt-2">
                    <button type="submit" class="btn btn-success btn-block">Publish</button>
                </div>
            </form>
        </div>
    </div>
</div>
       
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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>
 
Step 6: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Image Optimization In Laravel 9 Using Spatie
How To Image Optimization In L...

In this article, we will see how to image optimization in laravel 9 using spatie. Here, we will learn about image o...

Read More

Feb-10-2023

How to Create Select2 Dropdown in Laravel 10 Livewire
How to Create Select2 Dropdown...

Hello developers! Today, we're diving into the wonderful world of Laravel 10 and Livewire to create a Select2 d...

Read More

Feb-16-2024

How To Change Table Name Using Laravel 10 Migration
How To Change Table Name Using...

In this article, we will see how to change the table name using laravel 10 migration. Here, we will learn about the...

Read More

Apr-28-2023

How To Validate Phone Number Using jQuery
How To Validate Phone Number U...

In this article, we will see how to validate phone numbers using jquery. We will learn different methods of validat...

Read More

Oct-24-2022