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
How to Set Auto Database BackUp using Cron Scheduler In Laravel
How to Set Auto Database BackU...

In this article, we will see how to set auto database backup using the cron scheduler in laravel. here we will set ...

Read More

Feb-18-2021

Implement Secure SSO with OAuth2 in Laravel 11
Implement Secure SSO with OAut...

Hello, laravel web developers! In this tutorial, I'll show you how to implement a secure Single Sign-On (SSO) system...

Read More

Oct-16-2024

How to Run Specific Seeder in Laravel 8
How to Run Specific Seeder in...

In this example, we will learn how to run a specific seeder in laravel 8. If you want to run only one seeder in laravel...

Read More

Jan-19-2022

How To Install Vue 3 In Laravel 9 With Vite
How To Install Vue 3 In Larave...

In this article, we will see how to install Vue 3 in laravel 9 with vite. In the previous article, we will install...

Read More

Oct-10-2022