Image Upload using TinyMCE Editor in Laravel

Created at 29-Oct-2022 , By samar


Here in this article, we will learn how to upload images using TinyMCE editor in the Laravel application. You can upload images using TinyMCE and display them in your web page. 

TinyMCE is a rich text editor that allows uploading images from various sources. It has input options to paste the image source URL eg: (https://i.imgur.com/9g2IPEv.png) and you can choose images using (choose file) button by exploring the local images. Here we will upload images using the choose file option.

It will upload the image in the specified directory of the Laravel application. After uploading the image you can get the preview of the image in TinyMCE editor.

Here is the step by step instructions to upload images using TinyMCE editor

  1. Create a view file and call the tinyMCE plugin in it.
  2. Create a  route
  3. Create controller method 
  4. Disable VerifycsrfToken middleware for the route
  5. Run storage link command

Create a view file and call the tinyMCE plugin in it

We have to create a view file and after that we have to add a textarea field with tinymce cdn link and javascript code to initialize the plugin.

resources\views\<home>.blade.php

<textarea class="form-control" id="content" name="content"></textarea>
  
  
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector:'#content',
        height: 500,
        plugins: [
        'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
        'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
        'table emoticons template paste help codesample'
        ],

        image_title : true,
        automatic_uploads: true,
        images_upload_url : '/upload/post-image',
        file_picker_types: 'image',
        file_picker_callback: function (cv, value, meta){
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function(){
                var file = this.files[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                render.onload = function(){
                    var id = 'blobid'+(new Date()).getTime();
                    var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                    cb(blobInfo.blobUri(), {title:file.name});
                };
            };
            input.click();
        },
        toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
        'bullist numlist outdent indent | link image | print preview media fullpage | ' +
        'forecolor backcolor emoticons | help | codesample',
        menu: {
            favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | spellchecker | emoticons'}
        },
        menubar: 'favs file edit view insert format tools table help'
    });
    tinymce.activeEditor.execCommand('mceCodeEditor');
</script>

Create a  route

Now we have to create the route for uploading the image in web.php file under routes/web.php.

routes\web.php

Route::post('/upload/post-image', 'PostTaskController@uploadImage')->name('upload.post.image');

Create controller method

You have to create the controller using php artisan make:controller command and use below code that helps you to upload image.

Create controller using artisan command

php artisan make:controller PostTaskController

app\Http\Controllers\PostTaskController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostTaskController extends Controller
{
    public function uploadImage(Request $request){
        $imgpath = request()->file('file')->store('uploads', 'public');
        return response()->json(['location'=> "/storage/$imgpath"]);
    }
}

Disable VerifycsrfToken middleware for the route

app\Http\Middleware\VerifyCsrfToken.php

protected $except = [
    '/upload/post-image'
];

Run storage link command

php artisan storage:link

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.