How to Install and Use Trix Editor in Laravel 11?
In this article, I will show you how to install and use Trix Editor in laravel 11 application. we will use image upload with trix editor in laravel 11.
Trix Editor is a lightweight, rich text editor for the web, 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. It’s built with modern web technologies and integrates seamlessly into web applications, providing a clean, intuitive interface for creating and editing content.
In this example, we will create a simple use Trix editor with an image upload option that saves the image to local storage. We will set up three routes, we create one POST route to upload image. Once the user selects an image and submits it, the image will be stored in the 'media' folder.
So, let's see below the steps to getting done with image upload in trix Laravel.
Step for Image Upload with Trix Editor in Laravel 11
- Step 1: Install Laravel 11
- Step 2: Create Route
- Step 3: Create Controller
- Step 4: Create View File
- Run Laravel App:
Step 1: Install Laravel 11
First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:
composer create-project laravel/laravel example-app
Step 2: Create Route
In this step, we will add three routes with GET and POST method in routes/web.php file. so let's add it.
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
In this step, we have to create new controller as TrixController with index() and update() methods.
Make sure you have created media folder in your public directory because images will store on that folder.
so let's update follow code:
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;
}
}
}
Step 4: Create View File
In Last step, let's create trix.blade.php for display form with trix and put following code, we will also create attachments.js js file and put code on it.
resources/views/trix.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to Install and Use Trix Editor in Laravel 11? - ItSolutionStuff.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://unpkg.com/trix@2.0.8/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">How to Install and Use Trix Editor in Laravel 11? - ItSolutionStuff.com</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/trix@2.0.8/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 '';
}
})();
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/trix
Output:
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 11 MongoDB CRUD Application Tutorial
- Laravel 11 CORS Middleware Configuration Example
- How to Integrate Admin Template in Laravel 11?
- Laravel 11 Apexcharts using Larapex Charts Example
- Laravel 11 Socialite Login with Slack Account Example
- Laravel 11 Real-Time Notifications using Pusher Example
- Laravel 11 Socialite Login with Facebook Account Example
- Laravel 11 Socialite Login with Gitlab Account Example
- Laravel 11 Send Email Via Notification Example
- How to Send WhatsApp Messages With Laravel 11?
- Laravel 11 JSON Web Token(JWT) API Authentication Tutorial
- How to Install Bootstrap 5 in Laravel 11 with Vite?
- Laravel 11 Import Large CSV File into Database Example