├── .github
└── workflows
│ └── tests.yml
├── .styleci.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config
└── laravel-trix.php
├── database
└── migrations
│ └── create_trix_rich_texts_table.php.stub
├── logo.svg
├── resources
└── views
│ └── trixassets.blade.php
└── src
├── Http
└── Controllers
│ └── TrixAttachmentController.php
├── LaravelTrix.php
├── LaravelTrixServiceProvider.php
├── Models
├── TrixAttachment.php
└── TrixRichText.php
├── Pipes
├── AttachmentInput.php
├── Input.php
├── Styles.php
└── TrixEditor.php
└── Traits
└── HasTrixRichText.php
/.github/workflows/tests.yml:
--------------------------------------------------------------------------------
1 | name: tests
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - master
7 |
8 | jobs:
9 | tests:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v1
13 | - name: Setup PHP
14 | uses: shivammathur/setup-php@master
15 | with:
16 | php-version: 8.0
17 | - name: Install Composer
18 | run: composer install -q --no-ansi --no-interaction --no-scripts --no-suggest --no-progress --prefer-dist
19 | - name: run tests
20 | run: vendor/bin/phpunit
21 |
--------------------------------------------------------------------------------
/.styleci.yml:
--------------------------------------------------------------------------------
1 | preset: laravel
2 |
3 | disabled:
4 | - single_class_element_per_statement
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to `laravel-trix` will be documented in this file
4 |
5 | ## 1.0.0 - 2019-10-26
6 |
7 | - initial release
8 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are **welcome** and will be fully **credited**.
4 |
5 | Please read and understand the contribution guide before creating an issue or pull request.
6 |
7 | ## Etiquette
8 |
9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code
10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be
11 | extremely unfair for them to suffer abuse or anger for their hard work.
12 |
13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
14 | world that developers are civilized and selfless people.
15 |
16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
18 |
19 | ## Viability
20 |
21 | When requesting or submitting new features, first consider whether it might be useful to others. Open
22 | source projects are used by many developers, who may have entirely different needs to your own. Think about
23 | whether or not your feature is likely to be used by other users of the project.
24 |
25 | ## Procedure
26 |
27 | Before filing an issue:
28 |
29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
30 | - Check to make sure your feature suggestion isn't already present within the project.
31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
32 | - Check the pull requests tab to ensure that the feature isn't already in progress.
33 |
34 | Before submitting a pull request:
35 |
36 | - Check the codebase to ensure that your feature doesn't already exist.
37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
38 |
39 | ## Requirements
40 |
41 | If the project maintainer has any additional requirements, you will find them listed here.
42 |
43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
44 |
45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests.
46 |
47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
48 |
49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
50 |
51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
52 |
53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
54 |
55 | **Happy coding**!
56 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Ahmed Abd El Ftah
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | ## Configurable [Basecamp Trix Editor](https://trix-editor.org/) delivered to your laravel application
14 |
15 | inspired by [Rails Action Text](https://edgeguides.rubyonrails.org/action_text_overview.html)
16 |
17 |
18 | * [Installation](#installation)
19 | * [Usage](#usage)
20 | * [Using @trix($model, $field, $config = [])](#using-@trix($model,-$field,-$config-=-[]))
21 | * [Storing Rich Text Fields](#storing-rich-text-fields)
22 | * [Render Trix For Existing Model](#render-trix-for-existing-model)
23 | * [Storing Attachment](#storing-attachment)
24 | * [Changing Storage Disk](#changing-storage-disk)
25 | * [Configuration Table](#configuration-table)
26 | * [Testing](#testing)
27 |
28 | ## Installation
29 |
30 | You can install the package via composer:
31 |
32 | ```bash
33 | composer require te7a-houdini/laravel-trix
34 | ```
35 |
36 | Then publish the configurations and migrations:
37 |
38 | ```bash
39 | php artisan vendor:publish --provider="Te7aHoudini\LaravelTrix\LaravelTrixServiceProvider"
40 | ```
41 |
42 | After the migration has been published then run the migrations to create required tables:
43 |
44 | ```bash
45 | php artisan migrate
46 | ```
47 |
48 | then add `@trixassets` directive at the head tag of your html
49 | ```html
50 |
51 |
52 | @trixassets
53 |
54 |
55 | ```
56 |
57 |
58 | ## Usage
59 |
60 | let's assume we have `Post model` & want to add trix editor.
61 |
62 | ### Using @trix($model, $field, $config = [])
63 | you can use @trix directive inside any view to render trix editor.
64 |
65 | ```html
66 |
67 |
68 | @trixassets
69 |
70 |
71 |
72 |
73 | @trix(\App\Post::class, 'content')
74 |
75 |
76 |
77 | ```
78 |
79 | ### Storing Rich Text Fields
80 | now lets try to store `content` rich text field when hitting submit button.
81 |
82 | ```html
83 |
84 |
85 | @trixassets
86 |
87 |
88 |
89 |
94 |
95 |
96 |
97 | ```
98 | first add `HasTrixRichText` trait to your model
99 |
100 | ``` php
101 | namespace App;
102 |
103 | use Illuminate\Database\Eloquent\Model;
104 | use Te7aHoudini\LaravelTrix\Traits\HasTrixRichText;
105 |
106 | class Post extends Model
107 | {
108 | use HasTrixRichText;
109 |
110 | protected $guarded = [];
111 | }
112 | ```
113 | then you can easily store any rich text fields by multiple ways:
114 |
115 | ```php
116 | Post::create(request()->all());
117 |
118 | //storing must follow this convention (model lowered class name)-trixFields
119 | Post::create([
120 | 'post-trixFields' => request('post-trixFields'),
121 | ]);
122 |
123 | ```
124 |
125 |
126 | ### Render Trix For Existing Model
127 |
128 | there's multiple ways to render trix for already existing model
129 |
130 | ```php
131 |
132 |
133 | @trix($post, 'content')
134 |
135 | {!! $post->trix('content') !!} //must use HasTrixRichText trait in order for $model->trix() method work
136 |
137 | {!! app('laravel-trix')->make($post, 'content') !!}
138 | ```
139 |
140 | ### Render Html For Existing Model
141 |
142 | You can render the html content for already existing model
143 |
144 | ```php
145 |
146 |
147 | {!! $post->trixRender('content') !!} //must use HasTrixRichText trait in order for $model->trixRender() method work
148 | ```
149 |
150 | ### Storing Attachment
151 |
152 | when uploading a file to trix editor. an ajax request is sent to `store_attachment_action` in `laravel-trix` config file. which uses [Laravel Storage](https://laravel.com/docs/master/filesystem#introduction) and then this action returns `url` if upload is success according to [Basecamp Trix api](https://github.com/basecamp/trix#storing-attached-files) .
153 |
154 | the uploaded file will be stored in `trix_attachments` table as `pending` attachment.
155 |
156 | once model is saved . all `pending` attachments will have `is_pending` column = `0`
157 |
158 | so in order to make storing attachment very easy make sure to use `HasTrixRichText` trait in your model.
159 |
160 | ```php
161 | Post::create(request()->all());
162 |
163 | //storing must follow this convention (model lowered class name)-trixFields
164 | //and for attachment must follow attachment-(model lowered class name)-trixFields
165 | Post::create([
166 | 'post-trixFields' => request('post-trixFields'),
167 | 'attachment-post-trixFields' => request('attachment-post-trixFields')
168 | ]);
169 |
170 | ```
171 |
172 | ### Changing Storage Disk
173 |
174 | you can change attachment storage disk from `laravel-trix` config file .
175 |
176 | ```php
177 | return [
178 | 'storage_disk' => env('LARAVEL_TRIX_STORAGE_DISK', 'public'),
179 |
180 | 'store_attachment_action' => Te7aHoudini\LaravelTrix\Http\Controllers\TrixAttachmentController::class . '@store',
181 |
182 | 'destroy_attachment_action' => Te7aHoudini\LaravelTrix\Http\Controllers\TrixAttachmentController::class . '@destroy',
183 | ];
184 | ```
185 |
186 | or if you want to change the storage disk for specific rich text field you can do that
187 |
188 | ```php
189 | @trix($post, 'content', ['disk' => 'local'])
190 | ```
191 |
192 | ### Deleting Rich Text Field and Attachments
193 |
194 | you can remove related rich text fields and attachments on a model deleting:
195 |
196 | ```php
197 | class Post extends Model
198 | {
199 | use HasTrixRichText;
200 |
201 | protected $guarded = [];
202 |
203 | protected static function boot()
204 | {
205 | parent::boot();
206 |
207 | static::deleted(function ($post) {
208 | $post->trixRichText->each->delete();
209 | $post->trixAttachments->each->purge();
210 | });
211 | }
212 | }
213 | ```
214 |
215 | ### Configuration Table
216 |
217 | if you want to hide buttons or toolbar you can do this. for more configuration refer to the table below.
218 |
219 | ```php
220 | @trix($post, 'content', [ 'hideButtonIcons' => ['attach', 'bold'] ])
221 |
222 | @trix($post, 'content', [ 'hideTools' => ['text-tools'] ])
223 |
224 | ```
225 | | configuration | type | values | description
226 | |-----------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------
227 | | hideToolbar | Boolean | True or False | hides the the toolbar
228 | | hideTools | Array | ['text-tools', 'block-tools', 'file-tools', 'history-tools'] | hides group of buttons
229 | | hideButtonIcons | Array | ['attach', 'bold', 'italic', 'strike', 'link', 'heading-1', 'quote', 'code', 'bullet-list', 'number-list', 'decrease-nesting-level', 'increase-nesting-level'] | hides a single button
230 | | disk | String | 'local' or 's3' or 'any-disk' | sets the attachment storage per field
231 | | id | String | 'any-value-you-want' | the id of input which renders [trix. check this link](https://github.com/basecamp/trix#integrating-with-forms) . current id follows this convention `(model lowered class name)-field-modelId` like `post-content-1` or `post-content-new-model`
232 | | containerElement | String | valid html tag like `span` or `div` | default container tag is set to `span` you can change it as you want
233 |
234 |
235 | ### Testing
236 |
237 | ``` bash
238 | composer test
239 | ```
240 |
241 | ### Changelog
242 |
243 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
244 |
245 | ### Security
246 |
247 | If you discover any security related issues, please email ahmedabdelftah95165@gmail.com instead of using the issue tracker.
248 |
249 | ## Credits
250 |
251 | - [Ahmed Abd El Ftah](https://github.com/Te7a-Houdini)
252 | - [All Contributors](../../contributors)
253 |
254 | ## License
255 |
256 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
257 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "te7a-houdini/laravel-trix",
3 | "description": "trix editor for laravel inspired by ActionText for rails",
4 | "keywords": [
5 | "te7a-houdini",
6 | "laravel-trix"
7 | ],
8 | "homepage": "https://github.com/te7ahoudini/laravel-trix",
9 | "license": "MIT",
10 | "type": "library",
11 | "authors": [
12 | {
13 | "name": "Ahmed Abd El Ftah",
14 | "email": "ahmedabdelftah95165@gmail.com",
15 | "role": "Developer"
16 | }
17 | ],
18 | "require": {
19 | "php": "^7.1|^8.0",
20 | "laravel/framework": "~5.8.0|~6.0|~7.0|~8.0|~9.0|^10.0|^11.0|^12.0"
21 | },
22 | "require-dev": {
23 | "orchestra/testbench": "^3.5|~4.0|~5.0|~6.0|^8.0|^9.0|^10.0"
24 | },
25 | "autoload": {
26 | "psr-4": {
27 | "Te7aHoudini\\LaravelTrix\\": "src"
28 | }
29 | },
30 | "autoload-dev": {
31 | "psr-4": {
32 | "Te7aHoudini\\LaravelTrix\\Tests\\": "tests"
33 | }
34 | },
35 | "scripts": {
36 | "test": "vendor/bin/phpunit",
37 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage"
38 | },
39 | "config": {
40 | "sort-packages": true
41 | },
42 | "extra": {
43 | "laravel": {
44 | "providers": [
45 | "Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider"
46 | ]
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/config/laravel-trix.php:
--------------------------------------------------------------------------------
1 | env('LARAVEL_TRIX_STORAGE_DISK', 'public'),
5 |
6 | 'store_attachment_action' => Te7aHoudini\LaravelTrix\Http\Controllers\TrixAttachmentController::class.'@store',
7 |
8 | 'destroy_attachment_action' => Te7aHoudini\LaravelTrix\Http\Controllers\TrixAttachmentController::class.'@destroy',
9 | ];
10 |
--------------------------------------------------------------------------------
/database/migrations/create_trix_rich_texts_table.php.stub:
--------------------------------------------------------------------------------
1 | unsignedBigInteger('id')->autoIncrement();
18 | $table->string('field');
19 | $table->morphs('model');
20 | $table->text('content')->nullable();
21 | $table->timestamps();
22 | });
23 |
24 | Schema::create('trix_attachments', function (Blueprint $table) {
25 | $table->unsignedBigInteger('id')->autoIncrement();
26 | $table->string('field');
27 | $table->unsignedInteger('attachable_id')->nullable();
28 | $table->string('attachable_type');
29 | $table->string('attachment');
30 | $table->string('disk');
31 | $table->boolean('is_pending')->default(1);
32 | $table->timestamps();
33 | });
34 | }
35 |
36 | /**
37 | * Reverse the migrations.
38 | *
39 | * @return void
40 | */
41 | public function down()
42 | {
43 | Schema::drop('trix_attachments');
44 | Schema::drop('trix_rich_texts');
45 | }
46 | }
--------------------------------------------------------------------------------
/logo.svg:
--------------------------------------------------------------------------------
1 |
47 |
--------------------------------------------------------------------------------
/resources/views/trixassets.blade.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
137 |
--------------------------------------------------------------------------------
/src/Http/Controllers/TrixAttachmentController.php:
--------------------------------------------------------------------------------
1 | all(), [
17 | 'file' => 'required|file',
18 | 'modelClass' => 'required',
19 | 'field' => 'required',
20 | ]);
21 |
22 | if ($validator->fails()) {
23 | return response()->json(['errors'=>$validator->errors()], Response::HTTP_UNPROCESSABLE_ENTITY);
24 | }
25 |
26 | $attachment = $request->file->store('/', $request->disk ?? config('laravel-trix.storage_disk'));
27 |
28 | $url = Storage::disk($request->disk ?? config('laravel-trix.storage_disk'))->url($attachment);
29 |
30 | TrixAttachment::create([
31 | 'field' => $request->field,
32 | 'attachable_type' => $request->modelClass,
33 | 'attachment' => $attachment,
34 | 'disk' => $request->disk ?? config('laravel-trix.storage_disk'),
35 | ]);
36 |
37 | return response()->json(['url' => $url], Response::HTTP_CREATED);
38 | }
39 |
40 | public function destroy($url)
41 | {
42 | $attachment = TrixAttachment::where('attachment', basename($url))->first();
43 |
44 | return response()->json(optional($attachment)->purge());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/LaravelTrix.php:
--------------------------------------------------------------------------------
1 | model = $model;
25 |
26 | $this->loweredModelName = Str::lower(class_basename($model));
27 |
28 | $this->formatFieldConfig($field, $config);
29 |
30 | return $this;
31 | }
32 |
33 | public function formatFieldConfig($field, $config)
34 | {
35 | $config['id'] = $config['id'] ?? $this->loweredModelName.'-'.$field.'-'.(is_object($this->model) && $this->model->exists ? $this->model->id : 'new-model');
36 |
37 | $config['modelClass'] = is_object($this->model) ? get_class($this->model) : $this->model;
38 |
39 | $config['field'] = $field;
40 |
41 | $this->config = $config;
42 | }
43 |
44 | public function __toString()
45 | {
46 | return app(Pipeline::class)
47 | ->send($this)
48 | ->through([
49 | Styles::class,
50 | Input::class,
51 | AttachmentInput::class,
52 | TrixEditor::class,
53 | ])
54 | ->then($this->renderContainer());
55 | }
56 |
57 | public function renderContainer()
58 | {
59 | return function () {
60 | $tag = $this->config['containerElement'] ?? 'span';
61 |
62 | return "<$tag v-pre id='container-{$this->config['id']}'> $this->html $tag>";
63 | };
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/LaravelTrixServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->runningInConsole()) {
14 | $this->publishes([
15 | __DIR__.'/../config/laravel-trix.php' => config_path('laravel-trix.php'),
16 | ], 'config');
17 |
18 | $this->publishes([
19 | __DIR__.'/../database/migrations/create_trix_rich_texts_table.php.stub' => $this->app->databasePath().'/migrations/'.date('Y_m_d_His').'_create_trix_rich_texts_table.php',
20 | ], 'migrations');
21 | }
22 |
23 | Route::group([
24 | 'prefix' => 'laravel-trix',
25 | ], function () {
26 | Route::post('attachment', config('laravel-trix.store_attachment_action'))->name('laravel-trix.store');
27 | Route::delete('attachment/{attachment}', config('laravel-trix.destroy_attachment_action'))->name('laravel-trix.destroy');
28 | });
29 |
30 | $this->loadViewsFrom(__DIR__.'/../resources/views', 'laravel-trix');
31 |
32 | Blade::directive('trixassets', function () {
33 | return "render(); ?>";
34 | });
35 |
36 | Blade::directive('trix', function ($expression) {
37 | return "{!! app('laravel-trix')->make($expression) !!}";
38 | });
39 | }
40 |
41 | public function register()
42 | {
43 | $this->mergeConfigFrom(__DIR__.'/../config/laravel-trix.php', 'laravel-trix');
44 |
45 | $this->app->bind('laravel-trix', function ($app) {
46 | return $app->make(LaravelTrix::class);
47 | });
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/Models/TrixAttachment.php:
--------------------------------------------------------------------------------
1 | disk)->delete($this->attachment);
15 |
16 | $this->delete();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/Models/TrixRichText.php:
--------------------------------------------------------------------------------
1 | model) ? $trix->model->trixAttachments()->pluck('attachment') : '[]';
12 |
13 | $trix->html .= "";
14 |
15 | return $next($trix);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/Pipes/Input.php:
--------------------------------------------------------------------------------
1 | model) && $trix->model->exists ? htmlspecialchars(optional($trix->model->trixRichText()->where('field', $trix->config['field'])->first())->content, ENT_QUOTES) : old($trix->loweredModelName.'-trixFields.'.$trix->config['field'], '');
12 |
13 | $trix->html .= "";
14 |
15 | return $next($trix);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/Pipes/Styles.php:
--------------------------------------------------------------------------------
1 | hideToolBar($trix);
13 | $this->hideTools($trix);
14 | $this->hideButtonIcons($trix);
15 |
16 | $trix->html = " {$trix->html} ";
17 |
18 | return $next($trix);
19 | }
20 |
21 | public function hideToolBar($trix)
22 | {
23 | if (Arr::get($trix->config, 'hideToolbar')) {
24 | $trix->html .= "#container-{$trix->config['id']} trix-toolbar{display:none;}";
25 | }
26 | }
27 |
28 | public function hideTools($trix)
29 | {
30 | $trix->html .= collect(Arr::get($trix->config, 'hideTools', []))
31 | ->map(function ($tool) use ($trix) {
32 | return "#container-{$trix->config['id']} .trix-button-group--$tool";
33 | })
34 | ->implode(',').(Arr::get($trix->config, 'hideTools', []) ? '{display:none;}' : '');
35 | }
36 |
37 | public function hideButtonIcons($trix)
38 | {
39 | $trix->html .= collect(Arr::get($trix->config, 'hideButtonIcons', []))
40 | ->map(function ($iconClass) use ($trix) {
41 | return "#container-{$trix->config['id']} .trix-button--icon-$iconClass";
42 | })
43 | ->implode(',').(Arr::get($trix->config, 'hideButtonIcons', []) ? '{display:none;}' : '');
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Pipes/TrixEditor.php:
--------------------------------------------------------------------------------
1 | html .= "";
12 |
13 | return $next($trix);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/Traits/HasTrixRichText.php:
--------------------------------------------------------------------------------
1 | savedTrixFields = Arr::get($model, $trixInputName, []);
22 |
23 | $model->savedAttachments = Arr::get($model, 'attachment-'.$trixInputName, []);
24 |
25 | unset($model->$trixInputName);
26 | unset($model->{'attachment-'.$trixInputName});
27 | });
28 |
29 | static::saved(function ($model) {
30 | foreach ($model->savedTrixFields as $field => $content) {
31 | TrixRichText::updateOrCreate([
32 | 'model_id' => $model->id,
33 | 'model_type' => $model->getMorphClass(),
34 | 'field' => $field,
35 | ], [
36 | 'field' => $field,
37 | 'content' => $content,
38 | ]);
39 |
40 | $attachments = Arr::get($model->savedAttachments, $field, []);
41 |
42 | TrixAttachment::whereIn('attachment', is_string($attachments) ? json_decode($attachments) : $attachments)
43 | ->update([
44 | 'is_pending' => 0,
45 | 'attachable_id' => $model->id,
46 | ]);
47 | }
48 |
49 | $model->savedTrixFields = [];
50 | });
51 | }
52 |
53 | public function trix($field, $config = [])
54 | {
55 | return app('laravel-trix')->make($this, $field, $config);
56 | }
57 |
58 | public function trixRichText()
59 | {
60 | return $this->morphMany(TrixRichText::class, 'model');
61 | }
62 |
63 | public function trixAttachments()
64 | {
65 | return $this->morphMany(TrixAttachment::class, 'attachable');
66 | }
67 |
68 | public function trixRender($field)
69 | {
70 | return $this->trixRichText->where('field', $field)->first()->content;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------