Install and Use Trix Editor in Laravel 11

Websolutionstuff | Aug-28-2024 | Categories : Laravel

Hello, web developers! In this article, I will show you how to install and use Trix Editor in a Laravel 11 application, including image upload functionality. Trix Editor is a lightweight, rich text editor developed by Basecamp.

Designed for simplicity and ease of use, it offers essential text formatting features like bold, italics, links, and lists without overwhelming users with options.

Built with modern web technologies, Trix Editor integrates seamlessly into web applications, providing a clean and intuitive interface for creating and editing content.

In this example, we'll set up Trix Editor with an image upload feature that saves images to local storage. We'll configure three routes, including a POST route to handle image uploads.

When a user selects and submits an image, it will be stored in the 'media' folder

Laravel 11 Install Trix Editor Example

laravel 11 install trix editor

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Define Route

Now, we'll define the routes into the web.php file

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\TrixController;
  
Route::get('trix', [TrixController::class, 'index']);
Route::post('trix/upload', [TrixController::class, 'upload'])->name('trix.upload');
Route::post('trix/store', [TrixController::class, 'store'])->name('trix.store');

 

Step 3: Create Controller

Next, we'll create a controller and add the store and upload function to store the body and upload the image.

app/Http/Controllers/TrixController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TrixController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('trix');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        dd($request->body);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    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')->move(public_path('media'), $filenametostore);

            // you can save image path below in database
            $path = asset('media/'.$filenametostore);

            echo $path;
            exit;
        }
    }
}

Note: Create a media folder in your public directory.

 

Step 4: Create View File

Then, we'll create a blade file add the following HTML code to that file.

resources/views/trix.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Install and Use Trix Editor in Laravel 11 - Websolutionstuff</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/[email protected]/dist/trix.css">
    <style type="text/css">
        .trix-content img {
            width: 500px;
            height: 300px;
        }
    </style>
</head>
<body>
    
<div class="container">

    <div class="card mt-5">
        <h3 class="card-header p-3">Install and Use Trix Editor in Laravel 11 - Websolutionstuff</h3>
        <div class="card-body">
            <form action="{{ route('trix.store') }}" method="POST">
                @csrf

                <div class="form-group">
                    <strong>Title:</strong>
                    <input type="text" name="title" class="form-control" placeholder="Title" value="{{ old('title') }}">
                </div>
          
                <div class="form-group">
                    <strong>Slug:</strong>
                    <input type="text" name="slug" class="form-control" placeholder="Slug" value="{{ old('slug') }}">
                </div>
          
                <div class="form-group">
                    <strong>Body:</strong>
                    <input id="x" type="hidden" name="body">
                    <trix-editor input="x" class="trix-content"></trix-editor>
                </div>
          
                <div class="form-group mt-2">
                    <button class="btn btn-success" type="submit">Submit</button>
                </div>
          
            </form>
        </div>
    </div>
</div>
     
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/trix.umd.min.js"></script>
<script type="text/javascript">
    var fileUploadURL = "{{ route('trix.upload') }}";
</script>
<script src="{{ asset('js/attachments.js') }}"></script>

</body>
</html>

public/js/attachments.js

(function() {
    var HOST = fileUploadURL; //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 '';
      }
})();

 

Step 5: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
Laravel 10 Create AJAX Pagination Example
Laravel 10 Create AJAX Paginat...

In this article, we will see laravel 10 create an ajax pagination example. Here, we will learn about how to create...

Read More

Apr-17-2023

How to Download File on the FTP Server Using PHP
How to Download File on the FT...

Today we will see how to download file on the ftp server using php. Many time we have requirment to retrieve file from t...

Read More

May-21-2021

How To Get Current Week Records In MySQL
How To Get Current Week Record...

In this tutorial, we will see how to get current week records in MySQL. Many times we need to get current week reco...

Read More

Feb-07-2022

How To Create Custom Helper Function In Laravel 10
How To Create Custom Helper Fu...

In this article, we'll explore how to create a custom helper function in Laravel 10. This custom helper function can...

Read More

Mar-20-2023