Laravel CKEditor Implementation
Published: 2024-06-20 18:46:57


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.

```php
// 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');
```

## 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.

```html
<!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>
```

### View Blade File (view.blade.php)

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

```html
<!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>
```

## Step 3: Create the Controller

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

```php
<?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);
    }
}
```

## Step 4: Database Migration and Model

Create a migration and model for the `Ck` table.

```bash
php artisan make:model Ck -m
```

Update the migration file to include the necessary fields:

```php
public function up()
{
    Schema::create('cks', function (Blueprint $table) {
        $table->id();
        $table->text('content');
        $table->timestamps();
    });
}
```

Run the migration:

```bash
php artisan migrate
```

Update the `Ck` model:

```php
<?php

namespace App\Models;

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

class Ck extends Model
{
    use HasFactory;

    protected $fillable = ['content'];
}
```