CKEditor provides a rich text library where you can format the text very easily. It provides 200+ features to collaborate with text editing. Apart from the content, you can upload the image as well in CKEditor 5 in Laravel 8. The images can have full width and side alignment. If you are putting images within the content then you can set it as full width or side aligned. You can set the caption of the images. The best thing is everything will be stored as an HTML entity in the database. So, you can manage it very easily. In the previous tutorial, I had integrated the CKEditor 5 in the Laravel 8 application. Also, I had shown you how you can save the content in the database table. So, if you are a beginner then I recommend you go to my previous post first to conceive it better.
Now, its time to upload image in CKEditor 5 and save it into the database.
Prerequisites
For creating this Laravel 8 application, you will require the following tools –
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create Project to Upload Image in CKEditor 5
I have already created a project in the previous tutorial. I will continue to the same project. If you have landed to this post directly then create a new project first.
For creating the project, open the terminal and hit the below command.
composer create-project --prefer-dist laravel/laravel ckeditor
After creating the project, setup the database.
How to Create and Use Database Seeder in Laravel 8
Create and Configure Database
I have created a database with the below name.
CREATE DATABASE laravel_ckeditor;
Now, add the below credentials to establish the database connection.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ckeditor
DB_USERNAME=root
DB_PASSWORD=root
How to Create Pagination in Laravel 8 with Eloquent
Create Model, Migration, and Controller
I will generate the model, migration and the controller in a single line of command.
php artisan make:model -mc
Here, all the files are generated.
Now, you will have the post table migration file. So, just open it and replace the below data fields.
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title")->nullable();
$table->string("description")->nullable();
$table->timestamps();
});
}
Here, you have the table fields. Now, it’s time to set the fillable data into the model. So, that we can upload image in CKEditor 5.
<?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"
];
}
At last, migrate the post table using the migrate command followed by the path.
php artisan migrate --path=database/migrations/2020_10_10_060201_create_posts_table.php
Now, the migration has been completed. And the table is ready to synchronize with the model.
How to Use Guzzle Http in Laravel 8 For Request Handling
Upload Image in CKEditor 5
By default, the image upload functionality is not enabled in the CKEditor 5. It provides the cloud-based image upload. That means when you will choose the image, it will upload the image to the CKEditor Cloud Services for the fast uploading. So, we don’t need to store the image on our localhost. The CKEditor cloud service has a paid plan too. But for the initial, it gives a trial of one month.
You can follow the image upload document for more details. This is the syntax of the image upload in CKEditor 5.
ClassicEditor
.create( document.querySelector( '#editor' ), {
cloudServices: {
tokenUrl: 'https://example.com/cs-token-endpoint',
uploadUrl: 'https://your-organization-id.cke-cs.com/easyimage/upload/'
}
} )
.then( ... )
.catch( ... );
I have created an account in CKEditor cloud services and after verifying the account. I redirected to the dashboard.
Here, you will find the URL of the image upload. Also, here is a Token URL. It will require to pass in the script. So, just copy it and move to the next step.
How to Implement Yajra DataTables in Laravel 8
Create View To Upload Image in CKEditor 5
Here, I have created two views. In the first view, I have integrated the CKEditor 5 using the CDN. And then in the second view, I have listed the content from the database. Hence, create these views –
- create-post.blade.php
- index.blade.php
<!doctype html>
<html lang="en">
<head>
<title> Create Post - CKEditor 5 Example </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
{{-- CKEditor CDN --}}
<script src="https://cdn.ckeditor.com/ckeditor5/23.0.0/classic/ckeditor.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-12 text-right">
<a href="{{ url('post') }}" class="btn btn-danger"> Back </a>
</div>
</div>
<form action="{{url('save-post')}}" method="POST">
@csrf
<div class="row">
<div class="col-xl-8 col-lg-8 col-sm-12 col-12 m-auto">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ Session::get('success') }}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ Session::get('failed') }}
</div>
@endif
<div class="card shadow">
<div class="card-header">
<h4 class="card-title"> CK Editor Example in Laravel 8 </h4>
</div>
<div class="card-body">
<div class="form-group">
<label> Title </label>
<input type="text" class="form-control" name="title" placeholder="Enter the Title">
</div>
<div class="form-group">
<label> Description </label>
<textarea class="form-control" id="description" placeholder="Enter the Description" name="description"></textarea>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Save </button>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
ClassicEditor
.create( document.querySelector( '#description' ), {
cloudServices: {
tokenUrl: 'https://75402.cke-cs.com/token/dev/7798ed314adc402b84b88d5ccfc6097c65bda6b8a489e8692b60e7a975f5',
uploadUrl: 'https://75402.cke-cs.com/easyimage/upload/'
}
})
.catch( error => {
console.error( error );
} );
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
In the script, I have put the cloud service with the upload URL and the TokenUrl.
When you will select the image in the editor, this will upload the image to the CKEditor cloud services. Then the image will be reflected back to the editor as a preview.
<!doctype html>
<html lang="en">
<head>
<title> Post Listing </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
table td p {
word-break: break-all;
}
img {
width: 300px !important;
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="row">
<div class="col-xl-8">
<h3 class="text-right"> CK Editor Implementation in Laravel 8 </h3>
</div>
<div class="col-xl-4 text-right">
<a href="{{url('create-post')}}" class="btn btn-primary"> Add Post </a>
</div>
</div>
@if(count($posts) > 0)
<div class="table-responsive mt-4">
<table class="table table-striped">
<thead>
<tr>
<th> Id </th>
<th style="width:30%;"> Title </th>
<th> Decription </th>
</tr>
</thead>
<tbody>
@foreach($posts as $post)
<tr>
<td> {{ $post->id }} </td>
<td> {{ $post->title }} </td>
<td> {!! html_entity_decode($post->description) !!} </td>
</tr>
@endforeach
</tbody>
</table>
</div>
{{ $posts->links() }}
@endif
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
In the above blade file, I have rendered the data which will be coming from the controller. So, let’s move to the controller.
How to Send Emails Using Twilio Sendgrid in Laravel 8
Add Functionality in Controller
To save the content and upload image in CKEditor 5, you will have to add the functionality in the PostController.php.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
// post listing
public function index() {
$posts = Post::orderBy("id", "desc")->paginate(5);
return view("index", compact("posts"));
}
// Create Post
public function createPost() {
return view("create-post");
}
// Save New Post with Image
public function savePost(Request $request) {
$postArray = array(
"title" => $request->title,
"description" => $request->description
);
$post = Post::create($postArray);
if(!is_null($post)) {
return back()->with("success", "Success! Post created");
}
else {
return back()->with("failed", "Failed! Post not created");
}
}
}
How to Send Email Using Mailgun in Laravel 8
Add Routes
We will add the routes in the web.php file.
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::get('post', [PostController::class, "index"]);
Route::get("create-post", [PostController::class, "createPost"]);
Route::post('save-post', [PostController::class, "savePost"]);
Now, test the application for the expected result.
http://localhost:8000/create-post
For creating the post, we have the above URL. I have chosen the image with the content. And, I am able to select the image with the content. This is happening with the cloud service of the CKEditor.
It means, image has been uploaded to the CKEditor cloud services and it reflected in the editor.
Now, after hitting the save button, the content with image path will be stored in the database. Here, is the response. The post has been created in the database.
Now, we will see the result in the listing view.
Here, I have decoded the HTML entity to display the content. We have the result as we were expecting.
Create Auth Using Jetstream and Intertia js in Laravel 8
Conclusion
Lastly, we have uploaded the images using the CKEditor 5. The images have uploaded to the CKEditor Cloud Services. This is really very fast service, you can see the result. It won’t take time to upload the image. It will send the image directly to the cloud services after selecting it. Also, it reflects the image instantly in a micro seconds to the editor. Then we have stored the content in our local database. Also, we listed out the content in the view by decoding the HTML entity. So, I hope it will help you to upload the image in CKEditor 5.
Leave a Reply