How to Install and Use Trix Editor in Laravel

While managing a website, we always need a rich text editor(WYSIWYG). If you want to add descriptive content that contains HTML then WYSIWYG editor is the only choice. You can’t add such kind of content into the textarea. There are several rich text editors like TinyMCE, CKEditor are available on the Internet. Trix Editor is one of them. As a developer, you must have heard about Basecamp. The Trix editor is used in Basecamp for managing content. This is enough to say about the popularity of the Trix editor.

In this article, we study how to install and use the Trix editor in Laravel. We will also see how to upload images in the Trix editor.

Installation of Trix Editor

For getting started with Trix, you first need to include their JS and CSS file. You can find these files on their GitHub page under dist directory. Download 2 files trix.js and trix.css which will require soon.

As we need to include assets, create a ‘js’ and ‘css’ folder inside the public directory of your Laravel project. Place the copied JS and CSS files in respective directories.

Uploading images on the server using Trix requires you to add JavaScript code. So create a attachments.js file and keep it under public/js folder. We will add code to this file in the later part of the tutorial.

Add the following HTML into the blade file which will display Trix editor.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="{{ asset('/css/trix.css') }}">
</head>
<body>
    <form method="post" action={{ url('ROUTE_HERE') }}>
        {{ csrf_field() }}
        <p>
            <input id="x" type="hidden" name="content" value="" />
            <trix-editor input="x"></trix-editor>
        </p>
        <input type="submit" name="submit" value="Submit" />
    </form>
    
    <script src="{{ asset('js/trix.js') }}"></script>
    <script src="{{ asset('js/attachments.js') }}"></script>
</body>
</html>

The above HTML will display the Trix on your web page as shown in the screenshot below.

Trix Editor

Notice, we place the Trix editor in HTML using the trix-editor tag. The hidden field with the name ‘content’ is used to get or show content in Trix Editor. When we type anything inside Trix, the same content is set to this hidden field. On the server-side, we will get the content of the Trix editor using the below statement.

echo $request->input('content');

In the same way, if you want to display pre-filled content in Trix, then set the value to the hidden field as follows.

<input id="x" type="hidden" name="content" value="<h1>This is content</h1>" />

Upload Image in Trix Editor

If you want to use images in the content, then of course you need to upload the image on the server. Trix editor provides an event trix-attachment-add using which we will upload the image through Ajax. Let’s define a route for it.

Route::post('upload', 'ProductController@upload');

Adjust the Controller name in the route. In the upload method of Controller write the code as follows.

public function upload(Request $request)
{
    if($request->hasFile('file')) {
        //get filename with extension
        $filenamewithextension = $request->file('file')->getClientOriginalName();
 
        //get filename without extension
        $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
 
        //get file extension
        $extension = $request->file('file')->getClientOriginalExtension();
 
        //filename to store
        $filenametostore = $filename.'_'.time().'.'.$extension;
 
        //Upload File
        $request->file('file')->storeAs('public/uploads', $filenametostore);
 
        // you can save image path below in database
        $path = asset('storage/uploads/'.$filenametostore);

        echo $path;
        exit;
    }
}

Here, I am storing images under the public/uploads folder. You may need to create a symbolic link to the storage folder using the command:

php artisan storage:link

We have created a attachments.js file which will be used to give an Ajax call on the event trix-attachment-add. Add the code below in the attachments.js file.

(function() {
    var HOST = "http://localhost:8000/upload"; //pass the route
 
    addEventListener("trix-attachment-add", function(event) {
        if (event.attachment.file) {
            uploadFileAttachment(event.attachment)
        }
    })
 
    function uploadFileAttachment(attachment) {
        uploadFile(attachment.file, setProgress, setAttributes)
 
        function setProgress(progress) {
            attachment.setUploadProgress(progress)
        }
 
        function setAttributes(attributes) {
            attachment.setAttributes(attributes)
        }
    }
 
    function uploadFile(file, progressCallback, successCallback) {
        var formData = createFormData(file);
        var xhr = new XMLHttpRequest();
        
        xhr.open("POST", HOST, true);
        xhr.setRequestHeader( 'X-CSRF-TOKEN', getMeta( 'csrf-token' ) );
 
        xhr.upload.addEventListener("progress", function(event) {
            var progress = event.loaded / event.total * 100
            progressCallback(progress)
        })
 
        xhr.addEventListener("load", function(event) {
            var attributes = {
                url: xhr.responseText,
                href: xhr.responseText + "?content-disposition=attachment"
            }
            successCallback(attributes)
        })
 
        xhr.send(formData)
    }
 
    function createFormData(file) {
        var data = new FormData()
        data.append("Content-Type", file.type)
        data.append("file", file)
        return data
    }

    function getMeta(metaName) {
        const metas = document.getElementsByTagName('meta');
      
        for (let i = 0; i < metas.length; i++) {
          if (metas[i].getAttribute('name') === metaName) {
            return metas[i].getAttribute('content');
          }
        }
      
        return '';
      }
})();

In the above code, you should pass the route to HOST variable. Laravel requires a CSRF token in each request. We get this CSRF token from the HTML meta tag which we added in the blade file. When you add the image in Trix, it gives an Ajax call, uploads the image on the server, and returns the path of the uploaded image.

I hope you understand how to install and use the Trix editor in Laravel. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *