Certainly! Here’s a solution for integrating TipTap with Livewire for image uploads, along with some alternatives and reasoning.
Using TipTap with Livewire for Image Uploads
-
Frontend (TipTap Setup):
- Use TipTap’s
Imageextension and override its upload handler. - When a user selects an image, use JavaScript to upload the file via AJAX (e.g., using
fetchoraxios) to a Livewire endpoint. - On successful upload, insert the image URL into the editor.
- Use TipTap’s
-
Livewire Component:
- Create a method to handle the image upload and return the URL.
Example:
Blade View:
<div>
<div id="editor"></div>
<input type="hidden" wire:model="content">
</div>
Livewire Component (PHP):
use Livewire\Component;
use Livewire\WithFileUploads;
class Editor extends Component
{
use WithFileUploads;
public $content;
public function uploadImage()
{
$this->validate([
'image' => 'image|max:1024', // 1MB Max
]);
$path = $this->image->store('images', 'public');
return response()->json(['url' => asset('storage/' . $path)]);
}
public function render()
{
return view('livewire.editor');
}
}
JavaScript (TipTap Image Upload Handler):
import { Editor } from '@tiptap/core'
import Image from '@tiptap/extension-image'
const editor = new Editor({
element: document.querySelector('#editor'),
extensions: [
Image.extend({
addOptions() {
return {
...this.parent?.(),
inline: false,
allowBase64: false,
onUpload: async (file) => {
const formData = new FormData()
formData.append('image', file)
const response = await fetch('/livewire/message/editor/upload-image', {
method: 'POST',
body: formData,
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
})
const data = await response.json()
return data.url
}
}
}
}),
],
})
How it works:
- The user selects an image in TipTap.
- The custom upload handler sends the image to a Livewire endpoint.
- The endpoint stores the image and returns the URL.
- TipTap inserts the image using the returned URL.
Alternatives:
- Trix Editor: Has built-in support for file uploads, but less customizable than TipTap.
- Quill.js: Rich editor with image upload modules available.
- CKEditor: Powerful, but heavier and more complex to customize.
Why TipTap?
- Highly customizable and modern.
- Vue-based, but can be used with Alpine.js or plain JS.
- Great for advanced use-cases.
Summary:
TipTap with a custom image upload handler (AJAX to Livewire) is a solid approach. If you want a simpler setup, Trix or Quill are good alternatives, but TipTap offers the most flexibility for modern Laravel apps.
Let me know if you need a more detailed code example or help with a specific part!