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
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-example
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');
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.
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 '';
}
})();
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like:
In this article, we will see how to change the table name using laravel 10 migration. Here, we will learn about the...
Apr-28-2023
In this article, we will see how to add the bootstrap 5 modal in laravel 10. Here, we will learn about the bootstra...
Apr-12-2023
In this small tutorial i will show you how to implement bootstrap daterangepicker example, bootstrap date rang...
May-17-2021
Hello developers! In this article, we'll see how to create a custom error page in laravel 11. Here, we'll custom...
May-08-2024