DEV Community

Tahsin Abrar
Tahsin Abrar

Posted on

Laravel CKEditor Implementation

This documentation provides a step-by-step guide to implementing CKEditor in a Laravel project. The example includes setting up the CKEditor in an admin panel for content creation and displaying the content on a frontend view.

Prerequisites

  • Laravel installed on your local machine
  • Basic knowledge of Laravel framework and Blade templating engine

Step 1: Set Up Routes

Add the following routes to your web.php file to handle displaying the CKEditor form, viewing the content, and uploading images.

// frontend page
Route::get('ck-view', [CkController::class, 'ckView'])->name('ck-view');

// admin page
Route::get('ck-admin', [CkController::class, 'index'])->name('ck-admin');
Route::post('create', [CkController::class, 'store'])->name('create');
Route::post('update', [CkController::class, 'imageUpload'])->name('ck.upload');
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Blade Files

Admin Blade File (admin.blade.php)

Create a Blade file admin.blade.php for the admin panel where the CKEditor will be integrated.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>CkEditor</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-sm-8">
                <form method="POST" action="{{ route('create') }}">
                    @csrf
                    <input type="text" name="title" class="form-control mb-3" placeholder="Title">
                    <textarea name="editor" id="editor" class="form-control mt-3" placeholder="Description"></textarea>
                    <button class="btn-primary btn mt-3" type="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>
    <script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script>
    <script>
        ClassicEditor
            .create(document.querySelector('#editor'), {
                ckfinder: {
                    uploadUrl: '{{ route('ck.upload') . '?_token=' . csrf_token() }}',
                }
            })
            .catch(error => {
                console.error(error);
            });
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

View Blade File (view.blade.php)

Create a Blade file view.blade.php to display the content stored in the database.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>CkEditor</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body class="post-content">
    @foreach ($data as $note)
        {!! $note->content !!}
    @endforeach
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Controller

Create a CkController.php file and add the following code:

<?php

namespace App\Http\Controllers;

use App\Models\Ck;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CkController extends Controller
{
    public function ckView()
    {
        $data = Ck::all();
        return view('ck-view', compact('data'));
    }

    public function index()
    {
        return view('ck-admin');
    }

    public function store(Request $request)
    {
        $note = Ck::create([
            'content' => $request->input('editor'),
        ]);
        $request->session()->flash('success', 'Note created successfully.');

        return redirect()->route('ck-admin');
    }

    public function imageUpload(Request $request)
    {
        if ($request->hasFile('upload')) {
            try {
                $file = $request->file('upload');
                $extension = $file->getClientOriginalExtension();
                $randomFileName = Str::random(40) . '.' . $extension;
                $file->move(public_path('media'), $randomFileName);
                $url = asset('media/' . $randomFileName);

                return response()->json([
                    'fileName' => $randomFileName,
                    'uploaded' => 1,
                    'url' => $url,
                ]);
            } catch (\Exception $e) {
                Log::error('File upload error: ' . $e->getMessage(), [
                    'exception' => $e,
                    'trace' => $e->getTraceAsString(),
                    'request' => $request->all(),
                ]);
                return response()->json(['error' => 'File upload failed. Please try again.'], 500);
            }
        }

        return response()->json(['error' => 'No file uploaded.'], 400);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Database Migration and Model

Create a migration and model for the Ck table.

php artisan make:model Ck -m
Enter fullscreen mode Exit fullscreen mode

Update the migration file to include the necessary fields:

public function up()
{
    Schema::create('cks', function (Blueprint $table) {
        $table->id();
        $table->text('content');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Update the Ck model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Ck extends Model
{
    use HasFactory;

    protected $fillable = ['content'];
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay