Ckeditor Integration with Laravel File Manager in Laravel 8

Ckeditor Integration with Laravel File Manager in Laravel 8

Admin
Admin・ 20 Agustus 2021
24 min read ・ 6491 views

CKEditor di Laravel 8 - After in the previous article we discussed how to integrate TinyMCE 5 with the laravel file manager in laravel 8, so on this occasion I will share an article with a topic that is not much different, namely how to integrate CKEditor in laravel 8, complete with a Laravel File integration guide Managers. Before going into the steps of integrating CKEditor in laravel 8, we will first get acquainted with Ckeditor.

What is Ckeditor ?

Ckeditor is a text editor like WYSIWYG that allows writing content directly within web pages or applications. The core code of Ckeditor is created or written in Javascript and developed by CKSource. CKeditor is available in open source and premium versions.

When this article was written, Ckeditor is available in two versions namely Ckeditor 4 and CKEditor 5, and in this article we will discuss How to integrate CKEditor 4 in laravel 8.

Download CKEditor

integrasi ckeditor dengan laravel file manager di laravel

Before using or integrating CKEditor in laravel 8, we have to download CKEditor first. Ckeditor provides an option to download ckeditor, which can be directly downloaded using the command line, zip package, CDN or you can use an online builder. Online builder is a feature where we can choose what features we will use in a project with ckeditor. But later in this article, we will use the CDN option.

CKEditor integration in Laravel 8

After getting acquainted with CKEditor, it's time for us to try how to install or integrate CKEditor in laravel 8, which later we will also learn how to integrate CKEditor with laravel file manager in laravel 8.

Install Laravel

composer create-project laravel/laravel larackeditor

The first step we have to do, of course, is to install Laravel. Here I install the latest version of laravel (currently version 8) via composer. Open a terminal, go to the directory where the laravel project will be installed and then run the command as above. With this command, we will install the latest version of laravel (currently version 8) with the name larackeditor.

Install Laravel ui

In this experiment, we will create a case study as in the article on CKEditor integration in laravel 8, namely by installing ckeditor on the create Post page. To be able to enter the create post page, we must first login. So, to create a login or authentication feature in Laravel, we will install the Laravel UI package.

composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev

To create a login or authentication feature with laravel ui, first we have to go to the newly installed laravel directory with cd larackeditor and then run the above commands sequentially. *If there are errors or failures when running the command npm install && npm run dev, try repeating the command again or you can try npm install first, then run npm run dev.

Don't forget to create a new database for this CKEditor integration trial project in laravel 8 and adjust the DB_DATABASE in the .env file according to the newly created database name. Here I will create a new database with the name larackeditor.

php artisan migrate

Then if the database has been created and the .env file has been adjusted, continue to run migrate with the command as above.

Home page laravel ui

If the laravel ui install process is complete, please run the project then try to register, then it will be directed to the home page as shown above. Now, we will change this page later into a table view containing the post data that has been created.

Create Model & Migration

php artisan make:model Post -m

 

The next step is to create a model and migration file to create a post table which will later be used to accommodate post data created using the CKEditor text editor which is integrated with laravel version 8.

<?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->string('slug');
            $table->longText('desc');
            $table->timestamps();
        });
    }

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

Next, open the post migration file in the databases folder. usually filename format like [timestamp]_create_post_table.php. After that, adjust the code in the file with the code as above. In the post table, we will only create three fields, namely title, slug and desc. Well, this desc field will contain the data that we input with the CKEditor text editor which is integrated with laravel version 8. Save, and run php artisan migrate again.

Edit home.blade.php

As mentioned earlier, we will change the appearance of the home page to a posts table that contains dynamic post data that has been created on the create page. On the create page, we will integrate it with CKEditor. Open the file in resources/views/home.blade.php, then change all the code to be like below.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <a href="{{ route('create') }}" class="btn btn-success btn-sm mb-2">Create Post</a>
            <table class="table">
                <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col">Handle</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th scope="row">1</th>
                    <td>Mark</td>
                    <td>Otto</td>
                    <td>@mdo</td>
                  </tr>
                  <tr>
                    <th scope="row">2</th>
                    <td>Jacob</td>
                    <td>Thornton</td>
                    <td>@fat</td>
                  </tr>
                  <tr>
                    <th scope="row">3</th>
                    <td colspan="2">Larry the Bird</td>
                    <td>@twitter</td>
                  </tr>
                </tbody>
              </table>
        </div>
    </div>
</div>
@endsection

With the code above, we create a table and add a create button that points to the create route. Because route create has not been created in the route/web.php file, so we need to create it first. Add the route code below to the web.php file under the route home record.

Route::get('/create', [App\Http\Controllers\HomeController::class, 'create'])->name('create');

halaman home ckedtor 5 di laravel 8

Ok, now please try to open the home page. Then it will look like the image above. The data in the post table as shown above is still static, therefore we need to add a new function in HomeController.php, namely the function create which will direct us to the create view which will also be created.

Edit HomeController.php

public function create()
    {
        return view('create');
    }

In route web.php we have defined a create route that points to HomeController in the function create, but we don't have a function create in HomeController yet. Therefore we need to add a function create in HomeController with code like the image above. Open HomeController.php and add the above code to HomeController.php just below the function home. 

Create File create.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <form>
                <div class="mb-3">
                  <label for="title" class="form-label">Title</label>
                  <input type="text" class="form-control" id="title">
                </div>
                <div class="mb-3">
                  <label for="desc" class="form-label">Desc</label>
                  <textarea name="desc" class="my-editor form-control" id="my-editor" cols="30" rows="10"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
              </form>
        </div>
    </div>
</div> 
@endsection

@push('scripts')
<script src="//cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
<script>
    CKEDITOR.replace('my-editor');
    </script>
@endpush

Create a new view file with the name create.blade.php parallel to home.blade.php, then input the code as above. In the code above, we create 2 forms, namely title and desc (the slug is not made a form because the slug data will follow the title data). If we look at the code above, we push CDN CKEditor and init CKeditor.

@stack('scripts')

Then in the create.blade.php code we create a push(scripts) section, therefore please open the file in layouts/app.blade.php then add the @stack('scripts') code above the </body> tag.

tampilan ckeditor di laravel 8

If you have added @stack('scripts') in the app.blade.php file, now please open /create or click the create post button it will display as shown above. So far, we have successfully installed or integrated CKEditor with CDN in laravel 8. However, we have not been able to use the image upload feature.

Next we will install laravel file manager in this CKEditor integration exercise project in laravel 8. Laravel file manager functions to manage our files or images later. So later, it will be like in wordpress or blogger, we don't need to upload the same file for different posts. If we have used the file before, we just need to take the file from Laravel File Manager.

Install Laravel File Manager

composer require unisharp/laravel-filemanager
 php artisan vendor:publish --tag=lfm_config
 php artisan vendor:publish --tag=lfm_public
 php artisan storage:link

Next we will install the laravel file manager package from unisharp . We use this Laravel File Manager package in the CKEditor integration project in Laravel 8 for file or image management like in wordpress or blogger. Why do we choose this package from Unisharp? because Unisharp provides several mainstay features such as CKeditor & TinyMCE integration, uploading validatin, Cropping & Resizing of Images and others. To start using the laravel file manager package in CKEditor in laravel, please run the above commands in sequence.

php artisan vendor:publish --tag=lfm_config
php artisan vendor:publish --tag=lfm_public

The command above is the command to publish package config and assets

Edit .env

Edit the APP_URL in the .env file with your domain or project url. This means that if we run this CKEditor integration trial project in laravel 8 at URL 127.0.0.1:8000, we must also change the APP_URL with 127.0.0.1:8000. And if run on URL larackeditor.test, in APP_URL it should be larackeditor.test and so on.

Edit Route Web.php

Route::group(['prefix' => 'laravel-filemanager', 'middleware' => ['web', 'auth']], function () {
     \UniSharp\LaravelFilemanager\Lfm::routes();
 });

Open the web.php file in the routes folder, then add a route group like the code above. Look at the code above, we put the web auth middleware on the route group. That means if the user is not logged in and the user accesses the domain/laravel-filemanager, the user will be directed to the login page first.

Edit Create.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <form>
                <div class="mb-3">
                  <label for="title" class="form-label">Title</label>
                  <input type="text" class="form-control" id="title">
                </div>
                <div class="mb-3">
                  <label for="desc" class="form-label">Desc</label>
                  <textarea name="desc" class="my-editor form-control" id="my-editor" cols="30" rows="10"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
              </form>
        </div>
    </div>
</div> 
@endsection

@push('scripts')
<script src="//cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
<script>
  var options = {
    filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images',
    filebrowserImageUploadUrl: '/laravel-filemanager/upload?type=Images&_token=',
    filebrowserBrowseUrl: '/laravel-filemanager?type=Files',
    filebrowserUploadUrl: '/laravel-filemanager/upload?type=Files&_token='
  };
</script>
<script>
    CKEDITOR.replace('my-editor', options);
    </script>
@endpush

Then open the create.blade.php file again and replace all the code with the code as above (Here we adjust the script section). If you have, save and try to open the create page or rather please try the upload or insert image feature.

upload image di ckeditor dengan laravel file manager

Well done, we have successfully installed or integrated CKEditor by uploading an image using the laravel file manager in the CKEditor integration project in laravel 8. Next we will save the data that has been inputted on the create page to the database.

Save data Post to database

After learning how to install CKEditor in laravel 8, how to install and integrate laravel file manager in CKEditor, then we will continue to save the create post data to the database.

<form action="{{ route('store') }}" method="POST">
                @csrf
                <div class="mb-3">
                  <label for="title" class="form-label">Title</label>
                  <input type="text" name="title" class="form-control" id="title">
                </div>
                <div class="mb-3">
                  <label for="desc" class="form-label">Desc</label>
                  <textarea name="desc" class="my-editor form-control" id="my-editor" cols="30" rows="10"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
              </form>

Open the create.blade.php file, then change the form section to be like in the code example above. Here we will point the form to the route store (the route store we will create in the steps below).

Route::post('/create', [App\Http\Controllers\HomeController::class, 'store'])->name('store');

Open the route web.php file again and add the above code. In the route store, we will call the function store in the HomeController.php file, we will create the function in the steps below.

public function store(Request $request)
    {
        $data           = new \App\Models\Post;
        $data->title    = $request->title;
        $data->slug     = \Str::slug(request('title'));
        $data->desc     = $request->desc;
        $data->save();

        return redirect('home');
    }

Open the HomeController.php file and add a function store with the above code. The code above is a simple code example to run the input data command to the post table from the request that has been inputted on the form available on the create page. Now save, and try to enter the create page then enter text or content in the title and desc form then click submit. Then we will be directed to the home page and if we check in the Post table (database) the data that we have submitted has been entered but the data displayed on the home page is still static data. We will make slight changes to the home.blade.php and HomeController.php files so that the data displayed on the home page can be retrieved from the database.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <a href="{{ route('create') }}" class="btn btn-success btn-sm mb-2">Create Post</a>
            <table class="table">
                <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">Title</th>
                    <th scope="col">Slug</th>
                    <th scope="col">Desc</th>
                  </tr>
                </thead>
                <tbody>
                    @php
                        $no = 0;
                    @endphp
                  @foreach ($data as $data)
                  <tr>
                    <th scope="row">{{ ++$no }}</th>
                    <td>{{ $data->title }}</td>
                    <td>{{ $data->slug }}</td>
                    <td>{!! Str::limit( strip_tags( $data->desc ), 50 ) !!}</td>
                  </tr>
                  @endforeach

                </tbody>
              </table>
        </div>
    </div>
</div>
@endsection 

Open the home.blade.php file, then change all the code to be like the code above.

public function index()
    {
        $data = \App\Models\Post::all();
        return view('home',['data' => $data]);
    }

Then open the HomeController.php file, in the function index change it to be like the code above. Where if we look at the code above, we retrieve the data from the Post Model.

tampilan baru halaman home laravel

If the home.blade.php and HomeController.php files have been adjusted, now save the changes and try to see on the home page, the display will change to dynamically retrieving data from the database as shown above.

Then we also want to see what the post we've created previously looks like. For that we need to change the data in welcome.blade.php and add a new view file to see the details of the post.

Display Post

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>CKEditor Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
        <!-- Styles -->
        <style>
            /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}}
        </style>

        <style>
            body {
                font-family: 'Nunito', sans-serif;
            }
        </style>
    </head>
    <body class="antialiased">
        <div class="container">
            <div class="row">
                <div class="relative flex items-top justify-center min-h-screen sm:items-center py-4 sm:pt-0">
                    @if (Route::has('login'))
                        <div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
                            @auth
                                <a href="{{ url('/home') }}" class="text-sm text-gray-700 underline">Home</a>
                            @else
                                <a href="{{ route('login') }}" class="text-sm text-gray-700 underline">Log in</a>
        
                                @if (Route::has('register'))
                                    <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 underline">Register</a>
                                @endif
                            @endauth
                        </div>
                    @endif
        
                   @foreach ($post as $post)
                   <div class="col-md-4 m-2">
                    <div class="card">
                        <div class="card-body">
                          <h5 class="card-title">{{ $post->title }}</h5>
                          <p class="card-text">{!!  Str::limit( strip_tags( $post->desc ), 50 ) !!}</p>
                          <a href="{{ route('detail',$post->slug) }}" class="btn btn-primary">Detail</a>
                        </div>
                      </div>
                   </div>
                   @endforeach
        
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
    </body>
</html>

To be able to display post data, we will first change the code in the welcome.blade.php file. Open the welcome.blade.php file and then replace all the code with the above code. Here we will display post data in welcome.blade.php with card style and by adding bootstrap.

Route::get('/', function () {
    $post = \App\Models\Post::all();
    return view('welcome',['post' => $post]);
});

 

Then we need to change the welcome route a bit. Open the web.php file, and change it to be like the code above.
Route::get('/post/{slug}', function($slug) {
    $post = \App\Models\Post::where('slug',$slug)->firstOrFail();
    return view('detail',['post' => $post]);
})->name('detail');

Next we also need to add a new route to be able to display the details of the post. Add the code in the web.php file or rather under the welcome route.

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="card">
                <h5 class="card-header">Detail</h5>
                <div class="card-body">
                  <h5 class="card-title">{{ $post->title }}</h5>
                  <p class="card-text">{!! $post->desc !!}</p>
                </div>
              </div>
        </div>
    </div>
@endsection

Then, create a new view file parallel to home or welcome with the name detail.blade.php and enter the above code in the newly created detail file. After changing the web.php file, welcome.blade.php and adding the detail.blade.php file, let's see the result.

tampilan halaman welcome yang baru

The picture above is a new welcome screen after we make changes to the welcome.blade.php and web.php files. We can see, the welcome displays data taken from the database where the data was previously created on the /create page.

memasang atau integrasi CKEditor di laravel 8

And when on the welcome page we click on the details of one of the data (cards), then it will look like the picture above.

Conclusion

In this article we have learned how to use, how to install or how to integrate CKEditor with Laravel File Manager in laravel 8. Actually to install CKEditor in laravel 8 is quite easy and short, it's just that in this article we don't just learn to install CKEditor in laravel 8 but also learn how to integrate Laravel File Manager in CKEditor and learn how to implement CKEditor in a simple project created with laravel 8, so the steps in this article feel very long. CKEditor is one of the best text editors today with various free features provided and with a choice of version 4 and version 5.

That's an article about how to integrate CKEditor in Laravel 8 this time, if there are criticisms, suggestions, input or want to be discussed, please write them in the comment form below.

see you. 🚀 🚀

Reff:

  1. https://ckeditor.com/docs/ckeditor4/latest/index.html
  2. https://unisharp.github.io/laravel-filemanager/installation

Tinggalkan Komentar
Loading Comments