ᐊ back to home

Rich Text Laravel - Introduction

Tony Messias

Version 1.0.0 of the Rich Text Laravel package was released last week and I wanted to work on some content to showcase the package.

If you prefer video, I've recording a tutorial based on this post:

So, let's dive right in.

The Demo App

Before we start talking about Trix and how the package integrates Laravel with it, let's create a basic journaling application, where users can keep track of their thoughts (or whatever they want, really).

To create the Laravel application, let's use Laravel's installer:

1laravel new larajournal

I'm gonna be using Laravel Sail, so let's publish the docker-compose.yml file:

1php artisan sail:install --with=mysql

You will need Docker and Docker Compose installed, so make sure you follow their instructions. Also, feel free to use php artisan serve or Laravel Valet, if you want to. It doesn't really matter for what we're trying to do here.

Let's start the services:

1sail up -d

We should have both our database and the web server running. You can verify that by visiting http://localhost on your browser, or by listing the ps command, where all statuses should be Up:

1sail ps

Let's install the Breeze scaffolding so we can have basic authentication and a protected area scaffold for us:

1composer require laravel/breeze --dev
2php artisan breeze:install
3npm install && npm run dev

Now, we'll create the model with migration and factory:

1php artisan make:model Post -mf

Let's add a title and acontentfield to thecreate_posts_table` migration we have just created:

1Schema::create('posts', function (Blueprint $table) {
2 $table->id();
3 $table->foreignId('user_id')->constrained();
4 $table->string('title');
5 $table->longText('content');
6 $table->timestamps();
7});

We also added the Foreign Key to the users table so we can isolate each user's posts. Let's update the User model to add the posts relationship:

1class User extends Authenticatable
2{
3 use HasApiTokens, HasFactory, Notifiable;
4 
5 // ...
6 
7 public function posts()
8 {
9 return $this->hasMany(Post::class);
10 }
11}

Now, lets edit the DatabaseSeeder to create a default user and some posts as well as some random posts so we can just check that we don't see other user's posts:

1User::factory()->has(Post::factory(3))->create([
2 'name' => 'Test User',
3 'email' => 'user@example.com',
4]);
5 
6User::factory(5)->has(Post::factory(3))->create();

Now, let's edit the PostFactory so we can instruct it how to create new fake posts:

1<?php
2 
3namespace Database\Factories;
4 
5use App\Models\Post;
6use Illuminate\Database\Eloquent\Factories\Factory;
7 
8class PostFactory extends Factory
9{
10 protected $model = Post::class;
11 
12 public function definition()
13 {
14 return [
15 'title' => $this->faker->sentence(),
16 'content' => $this->faker->text(),
17 ];
18 }
19}

And edit the Post model to remove the mass-assignment protection:

1class Post extends Model
2{
3 use HasFactory;
4 
5 protected $guarded = [];
6}

Now, we can migrate and seed our database:

1sail artisan migrate --seed

Now, try to login with the user we created in our seeder. You should see the basic dashboard:

Breeze Dashboard

Now, let's pass down the user's post in the dashboard route at the web.php routes file:

1Route::get('/dashboard', function () {
2 return view('dashboard', [
3 'posts' => auth()->user()->posts()->latest()->get(),
4 ]);
5})->middleware(['auth'])->name('dashboard');

Now, make use of the posts variable in the dashboard.blade.php Blade file:

1<x-app-layout>
2 <x-slot name="header">
3 <div class="flex items-center justify-between">
4 <h2 class="text-xl font-semibold leading-tight text-gray-800">
5 {{ __('Dashboard') }}
6 </h2>
7 
8 <div>
9 <a href="{{ route('posts.create') }}" class="px-4 py-2 font-semibold text-indigo-400 border border-indigo-300 rounded-lg shadow-sm hover:shadow">New Post</a>
10 </div>
11 </div>
12 </x-slot>
13 
14 <div class="py-12">
15 <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
16 <div id="posts" class="space-y-5">
17 @forelse ($posts as $post)
18 <x-posts.card :post="$post" />
19 @empty
20 <x-posts.empty-list />
21 @endforelse
22 </div>
23 </div>
24 </div>
25</x-app-layout>

This view makes use of two components, which we'll add now. First, add the resources/views/components/posts/card.blade.php:

1<div class="bg-white border border-transparent rounded hover:border-gray-100 hover:shadow">
2 <a href="{{ route('posts.show', $post) }}" class="block w-full p-8">
3 <div class="pb-6 text-xl font-semibold border-b">
4 {{ $post->title }}
5 </div>
6 
7 <div class="mt-4">
8 {{ Str::limit($post->content, 300) }}
9 </div>
10 </a>
11</div>

This card makes use of a posts.show named route and the dashboard.blade.php file makes use of a posts.create named route, which doesn't yet exist. Let's add that. First, create the PostsController:

1php artisan make:controller PostsController

Then, add this to the web.php routes file:

1Route::resource('posts', Controllers\PostsController::class);

We're adding a resource route because we'll make use of other resource actions as well.

There's still one component missing from our dashboard.blade.php view, the x-posts.empty. This component we'll have an empty message to show when there are no posts for the current user. Create the empty-list.blade.php file at resources/views/components/posts/:

1<div class="p-3 text-center">
2 <p>There are no posts yet.</p>
3</div>

Now, you should be able to see the latest 3 fake posts for the current user in the dashboard.

Dashboard

So far, so good. However, if we click in the "New Post" link, nothing happens yet. Let's add the create action to the PostsController:

1/**
2 * Show the form for creating a new resource.
3 *
4 * @return \Illuminate\Http\Response
5 */
6public function create()
7{
8 return view('posts.create', [
9 'post' => auth()->user()->posts()->make(),
10 ]);
11}

This makes use of a posts.create view which doesn't yet exist. Create a resources/views/posts/create.blade.php file with the following content:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="text-xl font-semibold leading-tight text-gray-800">
4 <a href="{{ route('dashboard')}} ">Dashboard</a> / {{ __('New Post') }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
10 <div class="p-8 bg-white rounded-lg">
11 <div id="create_post">
12 <x-posts.form :post="$post" />
13 </div>
14 </div>
15 </div>
16 </div>
17</x-app-layout>

This makes use of a x-posts.form Blade component which we can create the resources/views/components/posts/form.blade.php file with the content:

1<form method="POST" action="{{ route('posts.store') }}">
2 @csrf
3 
4 <!-- Post Title -->
5 <div>
6 <x-label for="title" :value="__('Title')" />
7 
8 <x-input id="title" class="block w-full mt-1" placeholder="Type the title..." type="text" name="title" :value="old('title', $post->title)" required autofocus />
9 
10 <x-input-validation for="title" />
11 </div>
12 
13 <!-- Post Content -->
14 <div class="mt-4">
15 <x-label for="content" :value="__('Content')" class="mb-1" />
16 
17 <x-forms.richtext id="content" name="content" :value="$post->content" />
18 
19 <x-input-validation for="content" />
20 </div>
21 
22 
23 <div class="flex items-center justify-between mt-4">
24 <div>
25 <a href="{{ route('dashboard') }}">Cancel</a>
26 </div>
27 
28 <div class="flex items-center justify-end">
29 <x-button class="ml-3">
30 {{ __('Save') }}
31 </x-button>
32 </div>
33 </div>
34</form>

Almost all components used here comes with Breeze, except for the x-input-validation and the x-richtext components, which we'll add now. Create a resources/views/components/input-validatino.blade.php file with the contents:

1@props('for')
2 
3@if ($errors->has($for))
4 <p class="mt-1 text-sm text-red-800">{{ $errors->first($for) }}</p>
5@endif

For the richtext one, however, we're making it a simple textarea for now. Create the resources/components/forms/richtext.blade.php file with the content:

1@props(['disabled' => false, 'value' => ''])
2 
3<textarea {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'rounded-md shadow-sm border-gray-300 w-full focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50']) !!}>{{ $value }}</textarea>

Ok, now if you click in the "New Posts" link, we should see the create posts form. To be able to create a post, let's add the store action to the PostsController:

1/**
2 * Store a newly created resource in storage.
3 *
4 * @param \Illuminate\Http\Request $request
5 * @return \Illuminate\Http\Response
6 */
7public function store(Request $request)
8{
9 $request->user()->posts()->create($request->validate([
10 'title' => ['required'],
11 'content' => ['required'],
12 ]));
13 
14 return redirect()->route('dashboard');
15}

Alright, if you try to create a post, you will get redirected back to the dashboard route and you should see the new post at the top. Nice!

Now, let's implement the posts.show route. So, add a show action the PostsController:

1/**
2 * Display the specified resource.
3 *
4 * @param \App\Models\Post $post
5 * @return \Illuminate\Http\Response
6 */
7public function show(Post $post)
8{
9 return view('posts.show', [
10 'post' => $post,
11 ]);
12}

And create the view file at resources/views/posts/show.blade.php with the content:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="text-xl font-semibold leading-tight text-gray-800">
4 <a href="{{ route('dashboard') }}">Dashboard</a> / Post #{{ $post->id }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
10 <div class="p-8 bg-white rounded-lg">
11 <div class="relative">
12 <div class="pb-6 text-xl font-semibold border-b">
13 {{ $post->title }}
14 </div>
15 
16 <div class="absolute top-0 right-0" x-data x-on:click.away="$refs.details.removeAttribute('open')">
17 <details class="relative" x-ref="details">
18 <summary class="list-none" x-ref="summary">
19 <button type="button" x-on:click="$refs.summary.click()" class="text-gray-400 hover:text-gray-500">
20 <x-icon type="dots-circle" />
21 </button>
22 </summary>
23 
24 <div class="absolute right-0 top-6">
25 <ul class="w-40 px-4 py-2 bg-white border divide-y rounded rounded-rt-0">
26 <li class="py-2"><a class="block w-full text-left" href="{{ route('posts.edit', $post) }}">Edit</a></li>
27 <li class="py-2"><button class="block w-full text-left" form="delete_post">Delete</button></li>
28 </ul>
29 
30 <form id="delete_post" x-on:submit="if (! confirm('Are you sure you want to delete this post?')) { return false; }" action="{{ route('posts.destroy', $post) }}" method="POST">
31 @csrf
32 @method('DELETE')
33 </form>
34 </div>
35 </details>
36 </div>
37 </div>
38 
39 <div class="mt-4">
40 {{ $post->content }}
41 </div>
42 </div>
43 </div>
44 </div>
45</x-app-layout>

This view uses an x-icon component, which uses a Heroicons SVG. You can create with this:

1@props(['type'])
2 
3<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
4 @if ($type === 'dots-circle')
5 <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
6 @endif
7</svg>

With that, once you click in a post, you will see the entire post content. There's a dropdown here where you can see the "Edit" and "Delete" actions. Let's add the "destroy" action to the PostsController:

1/**
2 * Remove the specified resource from storage.
3 *
4 * @param \App\Models\Post $post
5 * @return \Illuminate\Http\Response
6 */
7public function destroy(Post $post)
8{
9 $post->delete();
10 
11 return redirect()->route('dashboard');
12}

This should make the delete action work. Now, let's create the edit action so we can edit posts. Add the edit and update actions to the PostsController:

1/**
2 * Show the form for editing the specified resource.
3 *
4 * @param \App\Models\Post $post
5 * @return \Illuminate\Http\Response
6 */
7public function edit(Post $post)
8{
9 return view('posts.edit', [
10 'post' => $post,
11 ]);
12}
13 
14/**
15 * Update the specified resource in storage.
16 *
17 * @param \Illuminate\Http\Request $request
18 * @param \App\Models\Post $post
19 * @return \Illuminate\Http\Response
20 */
21public function update(Request $request, Post $post)
22{
23 $post->update($request->validate([
24 'title' => ['required', 'min:3', 'max:255'],
25 'content' => ['required'],
26 ]));
27 
28 return redirect()->route('posts.show', $post);
29}

Next, add the edit.blade.php view at resources/views/posts/edit.blade.php with the contents:

1<x-app-layout>
2 <x-slot name="header">
3 <h2 class="text-xl font-semibold leading-tight text-gray-800">
4 <a href="{{ route('dashboard')}} ">Dashboard</a> / {{ __('Edit Post #:id', ['id' => $post->id]) }}
5 </h2>
6 </x-slot>
7 
8 <div class="py-12">
9 <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
10 <div class="p-8 bg-white rounded-lg">
11 <div id="edit_post">
12 <x-posts.form :post="$post" />
13 </div>
14 </div>
15 </div>
16 </div>
17</x-app-layout>

This will make use of the same form used to create posts, so we need to make some tweaks to it:

1<form
2 method="POST"
3 action="{{
4 $post->exists
5 ? route('posts.update', $post)
6 : route('posts.store')
7 }}"
8>
9 @csrf
10 @if ($post->exists)
11 @method('PUT')
12 @endif
13 
14 <!-- Post Title -->
15 <div>
16 <x-label for="title" :value="__('Title')" />
17 
18 <x-input id="title" class="block w-full mt-1" placeholder="Type the title..." type="text" name="title" :value="old('title', $post->title)" required autofocus />
19 
20 <x-input-validation for="title" />
21 </div>
22 
23 <!-- Post Content -->
24 <div class="mt-4">
25 <x-label for="content" :value="__('Content')" class="mb-1" />
26 
27 <x-forms.richtext id="content" name="content" :value="$post->content" />
28 
29 <x-input-validation for="content" />
30 </div>
31 
32 
33 <div class="flex items-center justify-between mt-4">
34 <div>
35 @if ($post->exists)
36 <a href="{{ route('posts.show', $post) }}">Cancel</a>
37 @else
38 <a href="{{ route('dashboard') }}">Cancel</a>
39 @endif
40 </div>
41 
42 <div class="flex items-center justify-end">
43 <x-button class="ml-3">
44 {{ __('Save') }}
45 </x-button>
46 </div>
47 </div>
48</form>

With these changes, the form will post to the update action if the post model already exists or to the create action if it's a new instance. Similarly, the cancel link will lead the user to dashboard if it's a new instance or to the posts.show route if the post already exists.

That's it for the first part of this tutorial. We now have a fully functioning basic application where users can create keep track of their thoughts. We're still using just a simple textarea field. It's time to install Trix and the Rich Text Laravel package.

Use the Rich Text Laravel Package

To install the package, we can run:

1composer require tonysm/rich-text-laravel

Next, run the package's install command:

1php artisan richtext:install

This will do:

  1. Publish the create_rich_texts_table migration
  2. Add trix to the package.json file as a dev dependency
  3. Publish the Trix bootstrap file to resources/js/libs/trix.js

Let's import that file in the resources/js/app.js file:

1require('./bootstrap.js');
2 
3require('alpinejs');
4 
5require('./libs/trix.js');

Then, add the Trix styles to the resources/css/app.css file:

1/** These are specific for the tag that will be added to the rich text content */
2.trix-content .attachment-gallery > .attachment,
3.trix-content .attachment-gallery > rich-text-attachment {
4 flex: 1 0 33%;
5 padding: 0 0.5em;
6 max-width: 33%;
7}
8 
9.trix-content .attachment-gallery.attachment-gallery--2 > .attachment,
10.trix-content .attachment-gallery.attachment-gallery--2 > rich-text-attachment,
11.trix-content .attachment-gallery.attachment-gallery--4 > .attachment,
12.trix-content .attachment-gallery.attachment-gallery--4 > rich-text-attachment {
13 flex-basis: 50%;
14 max-width: 50%;
15}
16 
17.trix-content rich-text-attachment .attachment {
18 padding: 0 !important;
19 max-width: 100% !important;
20}
21 
22/** These are TailwindCSS specific tweaks */
23.trix-content {
24 @apply w-full;
25}
26 
27.trix-content h1 {
28 font-size: 1.25rem !important;
29 line-height: 1.25rem !important;
30 @apply leading-5 font-semibold mb-4;
31}
32 
33.trix-content a:not(.no-underline) {
34 @apply underline;
35}
36 
37.trix-content ul {
38 list-style-type: disc;
39 padding-left: 2.5rem;
40}
41 
42.trix-content ol {
43 list-style-type: decimal;
44 padding-left: 2.5rem;
45}
46 
47.trix-content img {
48 margin: 0 auto;
49}

Let's install Trix and compile the assets:

1npm install && npm run dev

By default, the Rich Text Laravel package ships with a suggested database structure. All Rich Text contents will live in the rich_texts table. Now, we need to migrate our content field from the posts table and create rich_text entries for each existing post. If you're starting a new application with the package, you can skip this part. I just wanted to demo how you could do a simple migration.

Create the migration:

1php artisan make:migration migrate_posts_content_field_to_the_rich_text_table

Change the up method of the newly created migration to add the following content:

1foreach (DB::table('posts')->oldest('id')->cursor() as $post)
2{
3 DB::table('rich_texts')->insert([
4 'field' => 'content',
5 'body' => '<div>' . $post->content . '</div>',
6 'record_type' => (new Post)->getMorphClass(),
7 'record_id' => $post->id,
8 'created_at' => $post->created_at,
9 'updated_at' => $post->updated_at,
10 ]);
11}
12 
13Schema::table('posts', function (Blueprint $table) {
14 $table->dropColumn('content');
15});

Since the RichText model is a polymorphic one, let's enforce the morphmap so we avoid storing the class's FQCN in the database by adding the following line in the boot method of theAppServiceProvider:

1Relation::enforceMorphMap([
2 'post' => \App\Models\Post::class,
3]);

Now, let's add the HasRichText trait to the Post model and define our content field as a Rich Text field:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Factories\HasFactory;
6use Illuminate\Database\Eloquent\Model;
7use Tonysm\RichTextLaravel\Models\Traits\HasRichText;
8 
9class Post extends Model
10{
11 use HasFactory;
12 use HasRichText;
13 
14 protected $guarded = [];
15 
16 protected $richTextFields = [
17 'content',
18 ];
19}

Right now, the application is not working as you would expect. If you try to open it in the browser, you will see that it's not really behaving properly. First, we can see the <div> tag in the output both in the dashboard and in the posts.show routes. Let's fix the dashboard route first.

This will be a good opportunity to show a feature of the package: it can convert any Rich Text content to plain text! To achieve that, change the card component to be the following:

1-{{ Str::limit($post->content, 300) }}
2+{{ Str::limit($post->content->toPlainText(), 300) }}

Before, our content field was just a simple text field. Now, we get an instance of the RichText model, which forwards calls to the underlying Content class. The Content class has some really cool methods, such as the toPlainText() we see here.

With the card component taken care of, let's see what we can do for the posts.show route. It's still displaying the HTML tags. That's because Laravel's Blade will escape any HTML content when you're echoing out using double curly braces {{ }}, and that's not what we want. We need to let the HTML render on the page so any other tag such as h1s or ul created by Trix also display correctly.

Achieving that is relatively simple: use {!! !!} instead of @{{ }}. However, there's a serious gotcha here that allows malicious users to exploit an XSS attack. We'll talk more about that in the next section. For now, let's make the naive change:

1-{{ $post->content }}
2+{!! $post->content !!}

And voilà! The HTML tags are no longer being escaped and the HTML content is rendering again. Cool.

One last piece before we jump to the next section. We are still using a textarea in our form. Let's replace it with the Trix editor. Trix is already installed and assets should have been compiled earlier, so I think we're ready. Change the contents of the richtext form component to this:

1@props(['id', 'value', 'name', 'disabled' => false])
2 
3<input type="hidden" id="{{ $id }}_input" name="{{ $name }}" value="{{ $value?->toTrixHtml() }}" />
4<trix-editor id="{{ $id }}" input="{{ $id }}_input" {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'trix-content rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50']) !!}></trix-editor>

Open up the browser again and you should see the Trix editor! Ain't this cool? Make some changes to the content and submit the form. Everything should be working as before.

There are two HTML elements here to make Trix work as we want: the input and the trix-editor elements. The input is hidden, so users don't actually see it, but this is the input that will be submitted by the browser containing the latest state of the HTML content for our field. We feed it using the toTrixHtml() method that we get from our Content class. Trix will take care of keeping the state from the editor in sync with the value of the input field, so you don't have to worry about that.

Now, let's handle the XSS attack vector we enabled by outputting non-escaped HTML content.

HTML Sanitization

Before we fix the issue, let's exploit it ourselves. Go to your browser, open the create posts form, open up your DevTools, find and delete the trix-editor element and change the hidden input type to text so the input is displayed. Now, replace its value with a script tag, like so:

1<script>alert('hey, there');</script>

Submit the form and got to that post's show page. Oh, noes. The JavaScript was executed by the browser. We don't want that, right? We can fix it with a technique called HTML Sanitization. We don't actually need to allow the entire HTML spec to be rendered. We only need a subset of it so our rich text content is displayed correctly. So, for one, we don't need to render any <script> tag. We cannot use something like PHP's strip_tags function, because that would get rid of all tags, so our <b> or <a> tags would be gone. We could maybe pass it a list of allowed HTML tags, but we could still be exploited using some HTML attributes.

Instead, let's use a package that will handle most of the work for us. That's mews/purifier:

1composer require mews/purifier

The package gives us a clean() helper function that we can use to display sanitized. Let's change our posts/show.blade.php view to use that function:

1-{!! $post->content !!}
2+{!! clean($post->content) !!}

If you check that out in the browser you will notice that you no longer see the alert! So our problem was fixed. We still need to make some tweaks to the Sanitizer's default configs, but for now, that will do. Try out some rich text tweaks and see if they are displayed correctly. Most of them should.

Before we change the configs, let's explore one side of Trix that's not currently working: image uploads.

Simple Image Uploading

If you try to attach an image to Trix, it's not working out of the box. The image kinda shows up, but in a "pending" state, which means that this change was actually not made to the Trix document. See, Trix doesn't know how our application handles image upload, so it's up to us help it.

Let's use Alpine.js, which already comes installed with Breeze, to implement image uploading. First, let's cover the client-side of image uploading. Open up the richtext.blade.php component, and initialize Alpine in the trix-editor element:

1<trix-editor
2 x-data="{
3 // ...
4 }"
5></trix-editor>

Cool. Trix will dispatch a custom event called trix-attachment-add whenever you attempt to upload an attachment. We need to listen to that event and do the upload. The event will contain the file we have to upload as well as the Trix.Attachment instance object which we'll use later to set some attributes on it so we can tell Trix the attachment is no longer pending so it can update the Document state:

1@props(['id', 'value', 'name', 'disabled' => false])
2 
3<input
4 type="hidden"
5 id="{{ $id }}_input"
6 name="{{ $name }}"
7 value="{{ $value?->toTrixHtml() }}"
8/>
9<trix-editor
10 id="{{ $id }}"
11 input="{{ $id }}_input"
12 {{ $disabled ? 'disabled' : '' }}
13 {!! $attributes->merge(['class' => 'trix-content rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50']) !!}
14 x-data="{
15 upload(event) {
16 const data = new FormData();
17 data.append('attachment', event.attachment.file);
18 
19 window.axios.post('/attachments', data, {
20 onUploadProgress(progressEvent) {
21 event.attachment.setUploadProgress(
22 progressEvent.loaded / progressEvent.total * 100
23 );
24 },
25 }).then(({ data }) => {
26 event.attachment.setAttributes({
27 url: data.image_url,
28 });
29 });
30 }
31 }"
32 x-on:trix-attachment-add="upload"
33></trix-editor>

That's cool. We're sending a request to POST /attachments with an attachment field and we expect a image_url in the response data. Let's implement the server-side for that. We'll simply add a route Closure to our web.php routes file for now:

1Route::post('/attachments', function () {
2 request()->validate([
3 'attachment' => ['required', 'file'],
4 ]);
5 
6 $path = request()->file('attachment')->store('trix-attachments', 'public');
7 
8 return [
9 'image_url' => Storage::disk('public')->url($path),
10 ];
11})->middleware(['auth'])->name('attachments.store');

If you try to attach an image now, uploading should just work! But there should be a problem when you visit that post's show page: the image is broken. Let's publish the config so we can tweak it a little bit:

1php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider"

Now, open up the /config/purifier.php and replace its contents:

1<?php
2 
3return [
4 'encoding' => 'UTF-8',
5 'finalize' => true,
6 'ignoreNonStrings' => false,
7 'cachePath' => storage_path('app/purifier'),
8 'cacheFileMode' => 0755,
9 'settings' => [
10 'default' => [
11 'HTML.Doctype' => 'HTML 4.01 Transitional',
12 'HTML.Allowed' => 'rich-text-attachment[sgid|content-type|url|href|filename|filesize|height|width|previewable|presentation|caption|data-trix-attachment|data-trix-attributes],div,b,strong,i,em,u,a[href|title|data-turbo-frame],ul,ol,li,p[style],br,span[style],img[width|height|alt|src],del,h1,blockquote,figure[data-trix-attributes|data-trix-attachment],figcaption,pre,*[class]',
13 'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
14 'AutoFormat.AutoParagraph' => true,
15 'AutoFormat.RemoveEmpty' => true,
16 ],
17 'test' => [
18 'Attr.EnableID' => 'true',
19 ],
20 "youtube" => [
21 "HTML.SafeIframe" => 'true',
22 "URI.SafeIframeRegexp" => "%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/)%",
23 ],
24 'custom_definition' => [
25 'id' => 'html5-definitions',
26 'rev' => 1,
27 'debug' => false,
28 'elements' => [
29 // http://developers.whatwg.org/sections.html
30 ['section', 'Block', 'Flow', 'Common'],
31 ['nav', 'Block', 'Flow', 'Common'],
32 ['article', 'Block', 'Flow', 'Common'],
33 ['aside', 'Block', 'Flow', 'Common'],
34 ['header', 'Block', 'Flow', 'Common'],
35 ['footer', 'Block', 'Flow', 'Common'],
36 
37 // Content model actually excludes several tags, not modelled here
38 ['address', 'Block', 'Flow', 'Common'],
39 ['hgroup', 'Block', 'Required: h1 | h2 | h3 | h4 | h5 | h6', 'Common'],
40 
41 // http://developers.whatwg.org/grouping-content.html
42 ['figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'],
43 ['figcaption', 'Inline', 'Flow', 'Common'],
44 
45 // http://developers.whatwg.org/the-video-element.html#the-video-element
46 ['video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', [
47 'src' => 'URI',
48 'type' => 'Text',
49 'width' => 'Length',
50 'height' => 'Length',
51 'poster' => 'URI',
52 'preload' => 'Enum#auto,metadata,none',
53 'controls' => 'Bool',
54 ]],
55 ['source', 'Block', 'Flow', 'Common', [
56 'src' => 'URI',
57 'type' => 'Text',
58 ]],
59 
60 // http://developers.whatwg.org/text-level-semantics.html
61 ['s', 'Inline', 'Inline', 'Common'],
62 ['var', 'Inline', 'Inline', 'Common'],
63 ['sub', 'Inline', 'Inline', 'Common'],
64 ['sup', 'Inline', 'Inline', 'Common'],
65 ['mark', 'Inline', 'Inline', 'Common'],
66 ['wbr', 'Inline', 'Empty', 'Core'],
67 
68 // http://developers.whatwg.org/edits.html
69 ['ins', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']],
70 ['del', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']],
71 
72 // RichTextLaravel
73 ['rich-text-attachment', 'Block', 'Flow', 'Common'],
74 ],
75 'attributes' => [
76 ['iframe', 'allowfullscreen', 'Bool'],
77 ['table', 'height', 'Text'],
78 ['td', 'border', 'Text'],
79 ['th', 'border', 'Text'],
80 ['tr', 'width', 'Text'],
81 ['tr', 'height', 'Text'],
82 ['tr', 'border', 'Text'],
83 ],
84 ],
85 'custom_attributes' => [
86 ['a', 'target', 'Enum#_blank,_self,_target,_top'],
87 
88 // RichTextLaravel
89 ['a', 'data-turbo-frame', 'Text'],
90 ['img', 'class', new HTMLPurifier_AttrDef_Text()],
91 ['rich-text-attachment', 'sgid', new HTMLPurifier_AttrDef_Text],
92 ['rich-text-attachment', 'content-type', new HTMLPurifier_AttrDef_Text],
93 ['rich-text-attachment', 'url', new HTMLPurifier_AttrDef_Text],
94 ['rich-text-attachment', 'href', new HTMLPurifier_AttrDef_Text],
95 ['rich-text-attachment', 'filename', new HTMLPurifier_AttrDef_Text],
96 ['rich-text-attachment', 'filesize', new HTMLPurifier_AttrDef_Text],
97 ['rich-text-attachment', 'height', new HTMLPurifier_AttrDef_Text],
98 ['rich-text-attachment', 'width', new HTMLPurifier_AttrDef_Text],
99 ['rich-text-attachment', 'previewable', new HTMLPurifier_AttrDef_Text],
100 ['rich-text-attachment', 'presentation', new HTMLPurifier_AttrDef_Text],
101 ['rich-text-attachment', 'caption', new HTMLPurifier_AttrDef_Text],
102 ['rich-text-attachment', 'data-trix-attachment', new HTMLPurifier_AttrDef_Text],
103 ['rich-text-attachment', 'data-trix-attributes', new HTMLPurifier_AttrDef_Text],
104 ['figure', 'data-trix-attachment', new HTMLPurifier_AttrDef_Text],
105 ['figure', 'data-trix-attributes', new HTMLPurifier_AttrDef_Text],
106 ],
107 'custom_elements' => [
108 ['u', 'Inline', 'Inline', 'Common'],
109 
110 // RichTextLaravel
111 ['rich-text-attachment', 'Block', 'Flow', 'Common'],
112 ],
113 ],
114 
115];

If you refresh the browser now you will see that our img tag is now wrapped with a figure tag. But it's still not working, right?

That's because we need to symlink the storage folder to our public/ directory locally so images uploaded to the public disk using the local driver are displayed correctly:

1# If you're using Sail:
2sail artisan storage:link
3 
4# Otherwise, use this:
5php artisan storage:link

That should fix it! Great.

This will do it for an introductory guide, I think. I plan to write more advanced guides like User mentions and advanced image uploading using Spatie's Media Library package. I'll see you on the next post.