<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Codivores]]></title><description><![CDATA[Codivores]]></description><link>https://tech.codivores.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1681729201563/FZmOfuDdh.jpg</url><title>Codivores</title><link>https://tech.codivores.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 02:37:08 GMT</lastBuildDate><atom:link href="https://tech.codivores.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Twill / Vue 3 block party]]></title><description><![CDATA[Deep dive into Twill, a CMS package for Laravel, create reusable Twill and Vue blocks for your project]]></description><link>https://tech.codivores.com/ltivt-11-laravel-twill-vue3-block-party</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-11-laravel-twill-vue3-block-party</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Twill]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 21 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703150897793/e52f51db-a9bd-46e5-9aa5-0e025be3a683.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Now that we have set up all the tools to create blocks on both Twill and Vue sides, let's create some generic blocks.</p>
<p>Each block will be created in the <code>Common</code> namespace and will be manually added as an allowed block in the controller of our <code>PageContent</code> Module, and declared and called in our Module Inertia Page.</p>
<p>For example, for a <code>Codivores</code> block:</p>
<p><strong>/app/Http/Controllers/Admin/PageContentController.php</strong></p>
<pre><code class="lang-php">            BlockEditor::make()
                -&gt;withoutSeparator()
                -&gt;blocks([
                    <span class="hljs-string">'common-codivores'</span>,
                ])
</code></pre>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// &lt;script&gt;</span>
<span class="hljs-keyword">const</span> BlockCommonCodivores = defineAsyncComponent(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'@Block/Common/Codivores.vue'</span>))
<span class="hljs-comment">// &lt;/script&gt;</span>

<span class="hljs-comment">// &lt;template&gt;</span>
&lt;div
  v-<span class="hljs-keyword">for</span>=<span class="hljs-string">"(block, index) in item.blocks"</span>
  :key=<span class="hljs-string">"index"</span>
&gt;
  ...
  &lt;BlockCommonCodivores
    v-<span class="hljs-keyword">else</span>-<span class="hljs-keyword">if</span>=<span class="hljs-string">"block.type == 'common-codivores'"</span>
    :block=<span class="hljs-string">"block"</span>
  &gt;&lt;/BlockCommonCodivores&gt;
&lt;/div&gt;
<span class="hljs-comment">// &lt;/template&gt;</span>
</code></pre>
<h2 id="heading-separator-block">Separator Block</h2>
<p>Let's start with simple things; it is entirely possible to create a block without manageable content (this can also be the useful for blocks that will load asynchronously their content through Fetch API).</p>
<h3 id="heading-twill-block-component">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Separator.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Separator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Separator'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'more-dots'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor"><strong>Preview of the Twill BlockEditor</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703151719579/791e970f-54ef-4514-b856-cd8cdfee57e4.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703151746829/3d3fa92d-fde7-4b5a-ac2a-8d6d09d0b86a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/Separator.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonSeparator'</span>,
})
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto my-4 max-w-6xl"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full border-t border-gray-800"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page"><strong>Preview of the Inertia Page</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703153707616/8ba828cf-bbc9-413c-82a7-4db1d6022245.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-text-block">Text Block</h2>
<p>It's now time to enable HTML content in our blocks using Twill's WYSIWYG field.</p>
<p>To achieve this, we will enhance our BlockComponent class with new methods:</p>
<ul>
<li><p><code>fieldWysiwygTypeDefault()</code>: we will use the <code>quill</code> (<a target="_blank" href="https://quilljs.com/">https://quilljs.com</a>) editor instead of default <code>tiptap</code> (<a target="_blank" href="https://tiptap.dev/">https://tiptap.dev</a>)</p>
</li>
<li><p><code>fieldWysiwygToolbarOptionsDefault()</code>: our default toolbar with options that we decide to allow (it is also possible to add colorization with a list of hexadecimal codes)</p>
</li>
<li><p><code>fieldWysiwygToolbarOptionsLight()</code>: light toolbar that can be useful for certain content types</p>
</li>
</ul>
<p><strong>/app/View/Components/Twill/Blocks/Base/BlockComponent.php</strong></p>
<pre><code class="lang-php">...

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fieldWysiwygTypeDefault</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'quill'</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fieldWysiwygToolbarOptionsDefault</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            [<span class="hljs-string">'header'</span> =&gt; [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-literal">false</span>]],
            <span class="hljs-string">'bold'</span>,
            <span class="hljs-string">'italic'</span>,
            <span class="hljs-string">'underline'</span>,
            <span class="hljs-string">'strike'</span>,
            [<span class="hljs-string">'list'</span> =&gt; <span class="hljs-string">'bullet'</span>],
            [<span class="hljs-string">'list'</span> =&gt; <span class="hljs-string">'ordered'</span>],
            <span class="hljs-string">'link'</span>,
            <span class="hljs-string">'clean'</span>,
            <span class="hljs-comment">// ['color' =&gt; ["#747E8C", "#54D52B", "#3BA618", "#00B2D2", "#FBC000"]],</span>
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fieldWysiwygToolbarOptionsLight</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'bold'</span>,
            <span class="hljs-string">'italic'</span>,
            <span class="hljs-string">'clean'</span>,
        ];
    }

...
</code></pre>
<h3 id="heading-twill-block-component-1">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Text.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Wysiwyg</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Text</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Wysiwyg::make()
                -&gt;name(<span class="hljs-string">'content'</span>)
                -&gt;label(__(<span class="hljs-string">'Content'</span>))
                -&gt;type(<span class="hljs-built_in">self</span>::fieldWysiwygTypeDefault())
                -&gt;toolbarOptions(<span class="hljs-built_in">self</span>::fieldWysiwygToolbarOptionsDefault())
                -&gt;allowSource()
                -&gt;translatable(),
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Text'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'text'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor-1"><strong>Preview of the Twill BlockEditor</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703154504445/5db91471-28cd-4530-a166-11cfe91492f3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703154792078/c45094f5-4a4f-458c-81ae-93c61e04ff55.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component-1">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/Text.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonText'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">content</span>: {
    content?: string | <span class="hljs-literal">null</span>
  }
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.content?.content"</span>
    <span class="hljs-attr">v-html</span>=<span class="hljs-string">"block.content.content"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"text-gray-700 text-justify [&amp;&gt;p]:pb-4"</span>
  &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page-1"><strong>Preview of the Inertia Page</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703155350666/e4b7b235-5906-4de4-ac25-ba3f177bc57d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-button-block">Button Block</h2>
<p>Now, let's focus on buttons. In addition to a translatable <code>URL</code> and <code>label</code>, we will enable the selection of a type for <code>standard</code> (default) or <code>CTA</code> button.</p>
<p>A small Vue-side nuance: we will use the Inertia <code>Link</code> component for internal links and an HTML <code>&lt;a&gt;</code> tag with <code>target="_blank"</code> for external links.</p>
<h3 id="heading-twill-block-component-2">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Button.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Columns</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Select</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Option</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Options</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([

            Columns::make()
                -&gt;left([
                    Input::make()
                        -&gt;name(<span class="hljs-string">'label'</span>)
                        -&gt;label(__(<span class="hljs-string">'Label'</span>))
                        -&gt;translatable()
                        -&gt;required()
                ])
                -&gt;right([
                    Input::make()
                        -&gt;name(<span class="hljs-string">'url'</span>)
                        -&gt;label(__(<span class="hljs-string">'URL'</span>))
                        -&gt;translatable()
                        -&gt;required()
                ]),

            Select::make()
                -&gt;name(<span class="hljs-string">'type'</span>)
                -&gt;label(__(<span class="hljs-string">'Type'</span>))
                -&gt;options(
                    Options::make([
                        Option::make(<span class="hljs-string">'std'</span>, __(<span class="hljs-string">'Standard'</span>)),
                        Option::make(<span class="hljs-string">'cta'</span>, __(<span class="hljs-string">'Call To Action'</span>)),

                    ])
                )
                -&gt;default(<span class="hljs-string">'std'</span>)
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Button'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'revision-single'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor-2"><strong>Preview of the Twill BlockEditor</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703157514972/b392d200-cdfe-4106-a3f2-f6aa0a80ebe8.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703157543058/c0e80d18-96b8-473a-a454-0acc1c770eb1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component-2">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/Button.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'@inertiajs/vue3'</span>

defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonButton'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">content</span>: {
    label?: string | <span class="hljs-literal">null</span>
    url?: string | <span class="hljs-literal">null</span>
    type?: string | <span class="hljs-literal">null</span>
  }
}

<span class="hljs-keyword">const</span> props = defineProps&lt;Props&gt;()

<span class="hljs-keyword">const</span> classes = computed(<span class="hljs-function">() =&gt;</span>
  (props.block?.content?.type == <span class="hljs-string">'cta'</span>
    ? <span class="hljs-string">'bg-teal-600 hover:bg-teal-800 uppercase'</span>
    : <span class="hljs-string">'bg-gray-500 hover:bg-gray-700'</span>
  ).concat(<span class="hljs-string">' rounded px-5 py-3 font-bold text-white'</span>)
)
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.content?.url &amp;&amp; block.content?.label"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"flex justify-center my-2"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.content.url?.startsWith('http')"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
        <span class="hljs-attr">:href</span>=<span class="hljs-string">"block.content.url"</span>
        <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
      &gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">:class</span>=<span class="hljs-string">"classes"</span>&gt;</span>
          {{ block.content.label }}
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-else</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">:href</span>=<span class="hljs-string">"block.content.url"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">:class</span>=<span class="hljs-string">"classes"</span>&gt;</span>
          {{ block.content.label }}
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page-2"><strong>Preview of the Inertia Page</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703157626730/f2ac6ec7-b372-48d5-8113-9929296b0b98.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-image-block">Image Block</h2>
<p>Another type of content that will likely be used in a project is images. <a target="_blank" href="https://twillcms.com/docs/media-library/role-crop-params.html">Twill handles this exceptionally well with <code>medias</code></a></p>
<p>To streamline our workflow for media management, we will make some adaptations:</p>
<ul>
<li><p>Enhancing our <code>computeBlock()</code> method to handle medias and include only necessary information (src, height, width, alt, caption and video attributes)</p>
</li>
<li><p>Creating a <code>Picture</code> Vue component: naturally, you can customize the integration as you prefer or according to your project needs, and there are also solutions like <a target="_blank" href="https://www.twicpics.com">TwicPics</a> or <a target="_blank" href="https://imgix.com">Imgix</a> that not only offer CDN functionalities but also could display cropped images at the correct ratio automatically</p>
</li>
<li><p>Enriching our TypeScript types</p>
</li>
</ul>
<p>In this example, we will use Twill's standard <code>roles</code>, namely <code>desktop</code> (16/9), <code>tablet</code> (4/3), and <code>mobile</code> (1). Again, feel free to adapt these according to your preferences, depending on the project, the Module where it is used, ...</p>
<p><strong>/app/Models/Base/Model.php</strong></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Model</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillModel</span>
</span>{
    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">computeBlock</span>(<span class="hljs-params">$block, <span class="hljs-keyword">string</span> $locale, <span class="hljs-keyword">string</span> $fallbackLocale = <span class="hljs-literal">null</span></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-comment">// Handle medias.</span>
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($block-&gt;medias) &amp;&amp; count($block-&gt;medias) &gt; <span class="hljs-number">0</span>) {
            $medias = [];
            $roles = $block
                -&gt;medias
                -&gt;unique(<span class="hljs-string">'pivot.role'</span>)
                -&gt;pluck(<span class="hljs-string">'pivot.role'</span>);

            <span class="hljs-keyword">foreach</span> ($roles <span class="hljs-keyword">as</span> $role) {
                $images = $block-&gt;imagesAsArraysWithCrops($role);
                $medias[$role] = (is_array($images) &amp;&amp; count($images) &gt; <span class="hljs-number">1</span>) ? $images : reset($images);
            }

            $block-&gt;medias = $medias;
        }

...

        <span class="hljs-keyword">return</span> $block-&gt;only(Arr::collapse(
            [
                [
                    <span class="hljs-string">'editor_name'</span>,
                    <span class="hljs-string">'position'</span>,
                    <span class="hljs-string">'type'</span>,
                    <span class="hljs-string">'content'</span>,
                ],
                (count($block-&gt;medias) &gt; <span class="hljs-number">0</span>) ? [<span class="hljs-string">'medias'</span>] : [],
                ($block-&gt;childs &amp;&amp; count($block-&gt;childs) &gt; <span class="hljs-number">0</span>) ? [<span class="hljs-string">'childs'</span>] : []
            ]
        ));
    }
}
</code></pre>
<p><strong>/resources/views/Components/Theme/UI/Picture.vue</strong></p>
<pre><code class="lang-javascript">@@ <span class="hljs-number">-0</span>,<span class="hljs-number">0</span> +<span class="hljs-number">1</span>,<span class="hljs-number">121</span> @@
&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'ThemeUiPicture'</span>,
  <span class="hljs-attr">inheritAttrs</span>: <span class="hljs-literal">false</span>,
})

interface Props {
  media?: Model.Media | <span class="hljs-literal">null</span>
  mediaList?: Model.MediaWithRoles | <span class="hljs-literal">null</span>
  sizes?: number | object | <span class="hljs-literal">null</span>
  lazy?: boolean
  caption?: boolean
}

<span class="hljs-keyword">const</span> props = withDefaults(defineProps&lt;Props&gt;(), {
  <span class="hljs-attr">media</span>: <span class="hljs-literal">null</span>,
  <span class="hljs-attr">mediaList</span>: <span class="hljs-literal">null</span>,
  <span class="hljs-attr">lazy</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">caption</span>: <span class="hljs-literal">false</span>,
})

<span class="hljs-keyword">const</span> extensionList = [<span class="hljs-string">'webp'</span>, <span class="hljs-string">'jpg'</span>]

<span class="hljs-keyword">const</span> sizes =
  props.sizes &amp;&amp; <span class="hljs-keyword">typeof</span> props.sizes == <span class="hljs-string">'number'</span>
    ? {
        <span class="hljs-attr">mobile</span>: props.sizes,
        <span class="hljs-attr">tablet</span>: props.sizes,
        <span class="hljs-attr">desktop</span>: props.sizes,
        <span class="hljs-attr">default</span>: props.sizes,
      }
    : <span class="hljs-built_in">Object</span>.assign(
        {
          <span class="hljs-attr">mobile</span>: <span class="hljs-number">768</span>,
          <span class="hljs-attr">tablet</span>: <span class="hljs-number">1024</span>,
          <span class="hljs-attr">desktop</span>: <span class="hljs-number">1536</span>,
          <span class="hljs-attr">default</span>: <span class="hljs-number">1536</span>,
        },
        props.sizes
      )

<span class="hljs-keyword">const</span> figure = computed(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (props.mediaList !== <span class="hljs-literal">null</span> &amp;&amp; props.mediaList?.mobile &amp;&amp; props.mediaList?.tablet &amp;&amp; props.mediaList?.desktop) {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">sources</span>: [
        {
          <span class="hljs-attr">crop</span>: <span class="hljs-string">'mobile'</span>,
          <span class="hljs-attr">object</span>: props.mediaList.mobile,
          <span class="hljs-attr">size</span>: sizes.mobile,
          <span class="hljs-attr">media</span>: <span class="hljs-string">'(max-width: 768px)'</span>,
        },
        {
          <span class="hljs-attr">crop</span>: <span class="hljs-string">'tablet'</span>,
          <span class="hljs-attr">object</span>: props.mediaList.tablet,
          <span class="hljs-attr">size</span>: sizes.tablet,
          <span class="hljs-attr">media</span>: <span class="hljs-string">'(max-width: 1024px)'</span>,
        },
        {
          <span class="hljs-attr">crop</span>: <span class="hljs-string">'desktop'</span>,
          <span class="hljs-attr">object</span>: props.mediaList.desktop,
          <span class="hljs-attr">size</span>: sizes.desktop,
          <span class="hljs-attr">media</span>: <span class="hljs-string">'(min-width: 1025px)'</span>,
        },
      ],
      <span class="hljs-attr">caption</span>:
        props.caption &amp;&amp; props.mediaList.desktop?.caption &amp;&amp; props.mediaList.desktop.caption !== <span class="hljs-string">''</span>
          ? props.mediaList.desktop.caption
          : <span class="hljs-literal">null</span>,
    }
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (props.media) {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">sources</span>: [
        {
          <span class="hljs-attr">crop</span>: <span class="hljs-string">'default'</span>,
          <span class="hljs-attr">object</span>: props.media,
          <span class="hljs-attr">size</span>: sizes.default,
          <span class="hljs-attr">media</span>: <span class="hljs-string">'(min-width: 1px)'</span>,
        },
      ],
      <span class="hljs-attr">caption</span>: props.caption &amp;&amp; props.media?.caption &amp;&amp; props.media.caption !== <span class="hljs-string">''</span> ? props.media.caption : <span class="hljs-literal">null</span>,
    }
  }

  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
})
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">figure</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full h-auto"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"figure &amp;&amp; figure.sources"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">picture</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">template</span>
          <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(media, index) in figure.sources"</span>
          <span class="hljs-attr">:key</span>=<span class="hljs-string">"index"</span>
        &gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"media.object &amp;&amp; media.object.src"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">source</span>
              <span class="hljs-attr">v-for</span>=<span class="hljs-string">"imageFormat in extensionList"</span>
              <span class="hljs-attr">:srcset</span>=<span class="hljs-string">"`${media.object.src}&amp;fm=webp&amp;w=${media.size}`"</span>
              <span class="hljs-attr">:media</span>=<span class="hljs-string">"media.media"</span>
              <span class="hljs-attr">:type</span>=<span class="hljs-string">"`image/${imageFormat}`"</span>
            /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
              <span class="hljs-attr">v-if</span>=<span class="hljs-string">"index == figure.sources.length - 1"</span>
              <span class="hljs-attr">:src</span>=<span class="hljs-string">"`${media.object.src}&amp;fm=webp&amp;w=${media.size}`"</span>
              <span class="hljs-attr">:alt</span>=<span class="hljs-string">"media.object?.alt"</span>
              <span class="hljs-attr">v-bind</span>=<span class="hljs-string">"$attrs"</span>
              <span class="hljs-attr">:loading</span>=<span class="hljs-string">"lazy ? 'lazy' : 'eager'"</span>
              <span class="hljs-attr">class</span>=<span class="hljs-string">""</span>
            /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">picture</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">template</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">"caption &amp;&amp; figure.caption !== null"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">figcaption</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full text-xs text-center py-1"</span>&gt;</span>
          {{ figure.caption }}
        <span class="hljs-tag">&lt;/<span class="hljs-name">figcaption</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">figure</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<p><strong>/resources/js/types/models.d.ts</strong></p>
<pre><code class="lang-javascript">declare namespace Model {
  <span class="hljs-keyword">export</span> type Page = {
    ...
    medias: {} | <span class="hljs-literal">null</span>
  }

  <span class="hljs-keyword">export</span> type Media = {
    alt?: string
    caption?: string
    <span class="hljs-attr">height</span>: number
    src?: string
    video?: string
    <span class="hljs-attr">width</span>: number
  }

  <span class="hljs-keyword">export</span> type MediaWithRoles = {
    <span class="hljs-keyword">default</span>?: Media
    desktop?: Media
    mobile?: Media
    tablet?: Media
  }
}
</code></pre>
<h3 id="heading-twill-block-component-3">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Image.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Medias</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Image</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Medias::make()
                -&gt;name(<span class="hljs-string">'common_image'</span>)
                -&gt;label(__(<span class="hljs-string">'Image'</span>))
                -&gt;max(<span class="hljs-number">1</span>)
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCrops</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'common_image'</span> =&gt; [
                <span class="hljs-string">'desktop'</span> =&gt; [
                    [
                        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'desktop'</span>,
                        <span class="hljs-string">'ratio'</span> =&gt; <span class="hljs-number">16</span> / <span class="hljs-number">9</span>,
                        <span class="hljs-string">'minValues'</span> =&gt; [
                            <span class="hljs-string">'width'</span> =&gt; <span class="hljs-number">1200</span>,
                            <span class="hljs-string">'height'</span> =&gt; <span class="hljs-number">675</span>,
                        ],
                    ],
                ],
                <span class="hljs-string">'tablet'</span> =&gt; [
                    [
                        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'tablet'</span>,
                        <span class="hljs-string">'ratio'</span> =&gt; <span class="hljs-number">4</span> / <span class="hljs-number">3</span>,
                    ],
                ],
                <span class="hljs-string">'mobile'</span> =&gt; [
                    [
                        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'mobile'</span>,
                        <span class="hljs-string">'ratio'</span> =&gt; <span class="hljs-number">1</span>,
                    ],
                ],
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Image'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'image'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor-3"><strong>Preview of the Twill BlockEditor</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703167448502/1df18abd-62de-452d-b978-b9c2b8c57c46.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703167472679/a1f77ed8-8f6b-4692-a4c8-cb0f056bb021.png" alt class="image--center mx-auto" /></p>
<p>Then you can edit the crop for each role:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703167500597/091cb248-f8a6-47ae-bc44-c11c2890b549.png" alt="Desktop crop" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703168021978/329f8d40-aeb2-413f-84cf-9466497621d3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703167972244/3f0634e5-d36f-4a1d-9a94-a72479226a4b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component-3">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/Image.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Picture <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/UI/Picture.vue'</span>

defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonImage'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">medias</span>: {
    common_image?: Model.MediaWithRoles
  }
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.medias?.common_image"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"my-4"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Picture</span>
      <span class="hljs-attr">:mediaList</span>=<span class="hljs-string">"block.medias.common_image"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Picture</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page-3"><strong>Preview of the Inertia Page</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703169635528/36c65d76-8dd9-498b-961c-cc02206f035f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703169675540/4dd15d37-4f15-48e2-b422-b5510cf9d501.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-image-unconstrained-block">Image Unconstrained Block</h2>
<p>A more permissive version of the Image Block, with a single <code>role</code> and an unrestricted <code>free</code> ratio for unconstrained image display.</p>
<h3 id="heading-twill-block-component-4">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/ImageUnconstrained.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Medias</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ImageUnconstrained</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Medias::make()
                -&gt;name(<span class="hljs-string">'common_unconstrained_image'</span>)
                -&gt;label(__(<span class="hljs-string">'Image'</span>))
                -&gt;max(<span class="hljs-number">1</span>)
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCrops</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'common_unconstrained_image'</span> =&gt; [
                <span class="hljs-string">'default'</span> =&gt; [
                    [
                        <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'default'</span>,
                        <span class="hljs-string">'ratio'</span> =&gt; <span class="hljs-string">'free'</span>,
                    ],
                ],
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Unconstrained image'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'image'</span>;
    }
}
</code></pre>
<h3 id="heading-vue-3-block-component-4">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/ImageUnconstrained.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Picture <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/UI/Picture.vue'</span>

defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonImageUnconstrained'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">medias</span>: {
    common_unconstrained_image?: Model.MediaWithRoles
  }
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.medias?.common_unconstrained_image?.default"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"my-4"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Picture</span>
      <span class="hljs-attr">:media</span>=<span class="hljs-string">"block.medias.common_unconstrained_image.default"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Picture</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h2 id="heading-paragraph-block">Paragraph Block</h2>
<p>Just for fun, a component with conditional <code>title</code>, <code>subtitle</code> and <code>content</code>, that leverages our previous Text component for the <code>content</code> field.</p>
<h3 id="heading-twill-block-component-5">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Paragraph.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Wysiwyg</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Paragraph</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Input::make()
                -&gt;name(<span class="hljs-string">'title'</span>)
                -&gt;label(__(<span class="hljs-string">'Title'</span>))
                -&gt;translatable(),

            Input::make()
                -&gt;name(<span class="hljs-string">'subtitle'</span>)
                -&gt;label(__(<span class="hljs-string">'Subtitle'</span>))
                -&gt;translatable(),

            Wysiwyg::make()
                -&gt;name(<span class="hljs-string">'content'</span>)
                -&gt;label(__(<span class="hljs-string">'Content'</span>))
                -&gt;type(<span class="hljs-built_in">self</span>::fieldWysiwygTypeDefault())
                -&gt;toolbarOptions(<span class="hljs-built_in">self</span>::fieldWysiwygToolbarOptionsDefault())
                -&gt;allowSource()
                -&gt;translatable(),
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitleField</span>(<span class="hljs-params"></span>): ?<span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'title'</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Paragraph'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'content-editor'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor-4">Preview of the Twill BlockEditor</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703177565309/3a492cc1-2b97-4f25-a59e-359750333421.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703177621523/5f211f54-ce53-43af-bb4a-85b592e1d5d2.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component-5">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Common/Paragraph.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Text <span class="hljs-keyword">from</span> <span class="hljs-string">'./Text.vue'</span>

defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonParagraph'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">content</span>: {
    title?: string | <span class="hljs-literal">null</span>
    subtitle?: string | <span class="hljs-literal">null</span>
    content?: string | <span class="hljs-literal">null</span>
  }
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.content?.title || block?.content?.subtitle || block?.content?.content"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"my-4"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.content?.title"</span>
      <span class="hljs-attr">v-html</span>=<span class="hljs-string">"block.content.title"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"text-2xl font-bold mb-1"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.content?.subtitle"</span>
      <span class="hljs-attr">v-html</span>=<span class="hljs-string">"block.content.subtitle"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"text-xl font-semibold mb-1"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Text</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.content?.content"</span>
      <span class="hljs-attr">:block</span>=<span class="hljs-string">"block"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Text</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page-4">Preview of the Inertia Page</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703177715525/a91a0fd4-849f-4cf2-b7b6-7308225ff835.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-sandbox-pricing-plan-block">Sandbox - Pricing Plan Block</h2>
<p>An example to show the use of the Twill <code>InlineRepeater</code>, enabling the easy creation of dynamic content lists.</p>
<p>For the demonstration, we will create a pricing table.</p>
<h3 id="heading-twill-block-component-6">Twill Block component</h3>
<p><strong>/app/View/Components/Twill/Blocks/Sandbox/PricingTable.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Sandbox</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Columns</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Wysiwyg</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">InlineRepeater</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PricingTable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Input::make()
                -&gt;name(<span class="hljs-string">'title'</span>)
                -&gt;label(__(<span class="hljs-string">'Title'</span>))
                -&gt;translatable(),

            InlineRepeater::make()
                -&gt;name(<span class="hljs-string">'pricing'</span>)
                -&gt;label(__(<span class="hljs-string">'Plan'</span>))
                -&gt;triggerText(__(<span class="hljs-string">'Add a Plan'</span>))
                -&gt;fields([
                    Columns::make()
                        -&gt;left([
                            Input::make()
                                -&gt;name(<span class="hljs-string">'name'</span>)
                                -&gt;label(__(<span class="hljs-string">'Name'</span>))
                                -&gt;translatable()
                                -&gt;required(),
                        ])
                        -&gt;right([
                            Input::make()
                                -&gt;name(<span class="hljs-string">'price'</span>)
                                -&gt;label(__(<span class="hljs-string">'Price'</span>))
                                -&gt;required()
                                -&gt;type(<span class="hljs-string">'number'</span>)
                                -&gt;min(<span class="hljs-number">0</span>),
                        ]),

                    Wysiwyg::make()
                        -&gt;name(<span class="hljs-string">'description'</span>)
                        -&gt;label(__(<span class="hljs-string">'Description'</span>))
                        -&gt;type(<span class="hljs-built_in">self</span>::fieldWysiwygTypeDefault())
                        -&gt;toolbarOptions(<span class="hljs-built_in">self</span>::fieldWysiwygToolbarOptionsDefault())
                        -&gt;allowSource()
                        -&gt;translatable(),

                ])
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Pricing Table'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'b-checklist'</span>;
    }
}
</code></pre>
<h3 id="heading-preview-of-the-twill-blockeditor-5"><strong>Preview of the Twill BlockEditor</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703183126047/27abf648-0515-4533-8114-292be04bcc62.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703183149614/bfb9c9aa-5ba0-408d-a04e-d736c567662a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-vue-3-block-component-6">Vue 3 Block component</h3>
<p><strong>/resources/views/Components/Theme/Block/Sandbox/PricingTable.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockSandboxPricingTable'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">content</span>: {
    title?: string | <span class="hljs-literal">null</span>
    subtitle?: string | <span class="hljs-literal">null</span>
    content?: string | <span class="hljs-literal">null</span>
  }
  <span class="hljs-attr">childs</span>: PropsChildBlock[]
}

type PropsChildBlock = {
  <span class="hljs-attr">content</span>: {
    name?: string | <span class="hljs-literal">null</span>
    price?: string | <span class="hljs-literal">null</span>
    description?: string | <span class="hljs-literal">null</span>
  }
}

defineProps&lt;Props&gt;()

<span class="hljs-comment">/**
 * Tailwind dynamic classes.
 * opacity-60
 * opacity-80
 * opacity-100
 */</span>
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block?.childs &amp;&amp; Array.isArray(block.childs) &amp;&amp; block.childs.length &gt; 0"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full bg-blue pt-8"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.content?.title"</span>
      <span class="hljs-attr">v-html</span>=<span class="hljs-string">"block.content.title"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center text-4xl font-semibold text-gray-900 mb-8"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex justify-center"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">template</span>
        <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(child, index) in block.childs"</span>
        <span class="hljs-attr">:key</span>=<span class="hljs-string">"index"</span>
      &gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
          <span class="hljs-attr">v-if</span>=<span class="hljs-string">"child.content?.name &amp;&amp; child.content?.price"</span>
          <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full px-3"</span>
        &gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
            <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-teal-500 rounded-lg"</span>
            <span class="hljs-attr">:class</span>=<span class="hljs-string">"`opacity-${(3 + index) * 20}`"</span>
          &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-3 block text-3xl text-center font-semibold"</span>&gt;</span>
              {{ child.content.name }}
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-6 font-bold text-center"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-4xl"</span>&gt;</span>${{ child.content.price }}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-gray-600"</span>&gt;</span> / month <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>
              <span class="hljs-attr">v-if</span>=<span class="hljs-string">"child.content?.description"</span>
              <span class="hljs-attr">v-html</span>=<span class="hljs-string">"child.content.description"</span>
              <span class="hljs-attr">class</span>=<span class="hljs-string">"border-t border-stroke py-6 mx-6"</span>
            &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-preview-of-the-inertia-page-5"><strong>Preview of the Inertia Page</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703183358672/924e448a-1a10-4164-b5cf-6535cbbe72a0.png" alt class="image--center mx-auto" /></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Bridging Twill and Vue: crafting dynamic content Blocks]]></title><description><![CDATA[Deep dive into Twill, a CMS package for Laravel, create and publish dynamic content with reusable Twill and Vue blocks]]></description><link>https://tech.codivores.com/ltivt-10-laravel-twill-inertia-vue3-bridging-twill-vue-blocks</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-10-laravel-twill-inertia-vue3-bridging-twill-vue-blocks</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Twill]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Sun, 17 Dec 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703069681973/7b381238-77b3-4f70-8a61-348af89a4caa.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Now that we can create pages, it's time to leverage Twill's powerful content management features and construct reusable blocks.</p>
<p>In this article, we will focus on creating a basic <code>Title</code> Twill Block (with a translatable Twill Text Input in a <code>Common</code> namespace, using the Twill 3 formbuilder) and explore ways to enhance Developer Experience for subsequent blocks.</p>
<p>To achieve this, here are the different steps:</p>
<ol>
<li><p>Create a Twill Block component and add it to the BlockEditor of our <code>PageContent</code> Module</p>
</li>
<li><p>Improve our Twill Models to compute blocks data</p>
</li>
<li><p>Create a Vue 3 component for the Block</p>
</li>
<li><p>Use it in our <code>PageContent</code> Inertia Vue page</p>
</li>
</ol>
<h2 id="heading-twill-block-creation">Twill Block creation</h2>
<p>For detailed information, refer to the <a target="_blank" href="https://twillcms.com/docs/block-editor/creating-a-block-editor.html"><strong>official documentation</strong></a>.</p>
<h3 id="heading-generation">Generation</h3>
<p>A Block can be initiated with the CLI generator. Let's create a <code>Title</code> Block in the <code>Common</code> namespace.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># php artisan twill:make:componentBlock namespace.name</span>
php artisan twill:make:componentBlock common.title
</code></pre>
<p>The output we can see in our terminal:</p>
<pre><code class="lang-bash">Class written to /var/www/app/View/Components/Twill/Blocks/Common/Title.php
View written to /var/www/resources/views/components/twill/blocks/common/title.blade.php
</code></pre>
<h3 id="heading-files-generated">Files generated</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703065527958/318b4ed5-3190-4193-a2ad-5f2a2d3166aa.png" alt /></p>
<p>Since the view file is intended for rendering Blocks through Blade, it can be confidently removed.</p>
<p>The component class skeleton is as follows:</p>
<p><strong>/app/View/Components/Twill/Blocks/Common/Title.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Wysiwyg</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">TwillBlockComponent</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">View</span>\<span class="hljs-title">View</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Title</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillBlockComponent</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params"></span>): <span class="hljs-title">View</span>
    </span>{
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'components.twill.blocks.common.title'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Input::make()-&gt;name(<span class="hljs-string">'title'</span>),
            Wysiwyg::make()-&gt;name(<span class="hljs-string">'text'</span>)
        ]);
    }
}
</code></pre>
<p>We can see that the Block component main purpose is to define the form to manage its content and how render it.</p>
<p>As we</p>
<ul>
<li><p>won't use Blade engine for rendering, but we need to implement the <code>render()</code> method and return a <code>View</code></p>
</li>
<li><p>want to have just a translatable Text Input</p>
</li>
</ul>
<p>we can adapt the code this way:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">TwillBlockComponent</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">View</span>\<span class="hljs-title">View</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Title</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillBlockComponent</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params"></span>): <span class="hljs-title">View</span>
    </span>{
        <span class="hljs-keyword">return</span> view();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Input::make()
                -&gt;name(<span class="hljs-string">'title'</span>)
                -&gt;label(__(<span class="hljs-string">'Title'</span>))
                -&gt;translatable(),
        ]);
    }
}
</code></pre>
<h2 id="heading-adding-the-block-to-the-blockeditor-of-our-module"><strong>Adding the block to the BlockEditor of our Module</strong></h2>
<p>We already created a <a target="_blank" href="https://tech.codivores.com/ltivt-5-laravel-twill-first-module#heading-form-through-form-builder">BlockEditor field in our <code>PageContent</code> Form</a>, clicking on the <code>Add content</code> button, we can see our <code>Title</code> block in the dropdown with default Twill blocks:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703067178665/75d3d1d1-b492-4d1d-8057-bb839dbbee4c.png" alt class="image--center mx-auto" /></p>
<p>Selecting it, a translatable Text Input is displayed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703067245802/2fe505f8-3f0f-483b-bfa1-23858372cca3.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-twill-block-improvements">Twill Block improvements</h2>
<p>For now, we have seen the basics of a Block, but there are helpers that improve the experience. As we are going to create many blocks, a little refactoring would not be useless.</p>
<h3 id="heading-creating-a-blockcomponent-class-for-our-project"><strong>Creating a BlockComponent class for our project</strong></h3>
<p><strong>/app/View/Components/Twill/Blocks/Base/BlockComponent.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Base</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">TwillBlockComponent</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">View</span>\<span class="hljs-title">View</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlockComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillBlockComponent</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params"></span>): <span class="hljs-title">View</span>
    </span>{
        <span class="hljs-keyword">return</span> view();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockGroup</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">''</span>;
    }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Defines default <code>render()</code> and <code>getForm()</code> methods, preventing to implement it in every block</p>
</li>
<li><p>Overrides the <code>getBlockGroup()</code> helper, that returns <code>app-</code> by default for every block and does not represent our code organization</p>
</li>
</ul>
<blockquote>
<p>We will see later, but this class will allow us, for example, to globally define the default editor and toolbar of WYSIWYG fields, ...</p>
</blockquote>
<h3 id="heading-creating-a-base-block-class-for-our-namespace"><strong>Creating a Base Block class for our namespace</strong></h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Base.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">BlockComponent</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Base</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BlockComponent</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockGroup</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'common-'</span>;
    }
}
</code></pre>
<p>Its purpose is essentially to define the group for all blocks in the namespace.</p>
<h3 id="heading-and-now-our-block">And now our Block</h3>
<p><strong>/app/View/Components/Twill/Blocks/Common/Base.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Blocks</span>\<span class="hljs-title">Common</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Title</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params"></span>): <span class="hljs-title">Form</span>
    </span>{
        <span class="hljs-keyword">return</span> Form::make([
            Input::make()
                -&gt;name(<span class="hljs-string">'title'</span>)
                -&gt;label(__(<span class="hljs-string">'Title'</span>))
                -&gt;translatable(),
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitleField</span>(<span class="hljs-params"></span>): ?<span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'title'</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockTitle</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> __(<span class="hljs-string">'Title'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getBlockIcon</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'wysiwyg_header'</span>;
    }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Extends our Base Block in our <code>Common</code> namespace</p>
</li>
<li><p>Provides a dynamic title with <code>getBlockTitleField()</code> using the <code>title</code> field. It's not mandatory but can be helpful when there are many blocks in the BlockEditor (you can also remove the Block title prefix overriding <code>shouldHidePrefix()</code> method)</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703068780933/aef3469a-70a0-4769-bed4-4e1ed6975b4e.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Customizes the title with <code>getBlockTitle()</code> and the icon with <code>getBlockIcon()</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703069108870/3902bf64-4831-4193-9009-21aa726c96d6.png" alt /></p>
</li>
</ul>
<h3 id="heading-filtering-allowed-blocks-on-our-module-optional"><strong>Filtering allowed blocks on our module</strong> [optional]</h3>
<p>In the BlockEditor field, it is possible to define the list of allowed blocks. Depending on the page templates and the number of blocks in your project, it could be a good practice to define exactly the list of available blocks for each Module.</p>
<p>Taking the controller of our <code>PageContent</code> Module, in the <code>getForm()</code> method, we will call the <code>blocks()</code> method, giving it the list of the blocks.</p>
<p><strong>/app/Http/Controllers/Twill/PageContentController.php</strong></p>
<pre><code class="lang-php">...    

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params">TwillModelContract $model</span>): <span class="hljs-title">Form</span>
    </span>{
        $form = <span class="hljs-built_in">parent</span>::getForm($model);

        $form-&gt;add(
            BlockEditor::make()
                -&gt;withoutSeparator()
                -&gt;blocks([
                    <span class="hljs-string">'common-title'</span>,
                ])
        );

        <span class="hljs-keyword">return</span> $form;
    }

...
</code></pre>
<h2 id="heading-lets-take-a-look-on-the-frontend-side">Let's take a look on the frontend side</h2>
<p>A Twill Block component is a Laravel Eloquent Model and therefore contains a lot of information (attributes, relations, ...) that are not necessary.</p>
<p>Here is what it looks like if we inject the block as is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703069583342/3205f11b-7f9f-46d5-886c-a28a82fc7472.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-lets-create-a-base-model-with-some-methods-to-prepare-the-blocks-data">Let's create a Base Model with some methods to prepare the Blocks data</h3>
<p>We will create a Model that extends Twill's Model in which we will add a method to prepare Block data.</p>
<blockquote>
<p>For now, we will just handle the blocks, but this class will also allow us to manage Model medias, files, slug, and also medias, browsers, ... in blocks</p>
</blockquote>
<p><strong>/app/Models/Base/Model.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Base</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Model</span> <span class="hljs-title">as</span> <span class="hljs-title">TwillModel</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Arr</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Model</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillModel</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">computeBlocks</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $locale = <span class="hljs-literal">null</span></span>): <span class="hljs-title">void</span>
    </span>{
        $locale = $locale ?? app()-&gt;getLocale();
        $fallbackLocale = config(<span class="hljs-string">'translatable.use_property_fallback'</span>, <span class="hljs-literal">false</span>) ? config(<span class="hljs-string">'translatable.fallback_locale'</span>) : $locale;

        $blocks = <span class="hljs-keyword">$this</span>-&gt;blocks
            -&gt;where(<span class="hljs-string">'parent_id'</span>, <span class="hljs-literal">null</span>)
            -&gt;map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$block</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$locale, $fallbackLocale</span>) </span>{
                $block-&gt;childs = <span class="hljs-keyword">$this</span>-&gt;blocks
                    -&gt;where(<span class="hljs-string">'parent_id'</span>, $block-&gt;id)
                    -&gt;map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$blockChild</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$locale, $fallbackLocale</span>) </span>{
                        $blockChild-&gt;childs = <span class="hljs-keyword">$this</span>-&gt;blocks
                            -&gt;where(<span class="hljs-string">'parent_id'</span>, $blockChild-&gt;id)
                            -&gt;map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$blockChildChild</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$locale, $fallbackLocale</span>) </span>{
                                <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;computeBlock($blockChildChild, $locale, $fallbackLocale);
                            })
                            -&gt;values();

                        $block = <span class="hljs-keyword">$this</span>-&gt;computeBlock($blockChild, $locale, $fallbackLocale);
                        <span class="hljs-keyword">return</span> $block;
                    })
                    -&gt;values();

                $block-&gt;unsetRelation(<span class="hljs-string">'children'</span>);

                <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;computeBlock($block, $locale, $fallbackLocale);
            })-&gt;values();

        <span class="hljs-keyword">$this</span>-&gt;unsetRelation(<span class="hljs-string">'blocks'</span>);
        <span class="hljs-keyword">$this</span>-&gt;blocks = $blocks-&gt;values();
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">computeBlock</span>(<span class="hljs-params">$block, <span class="hljs-keyword">string</span> $locale, <span class="hljs-keyword">string</span> $fallbackLocale = <span class="hljs-literal">null</span></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-comment">// Handle translated content inputs.</span>
        <span class="hljs-keyword">if</span> (is_array($block-&gt;content) &amp;&amp; count($block-&gt;content) &gt; <span class="hljs-number">0</span>) {
            $blockContent = $block-&gt;content;
            <span class="hljs-keyword">foreach</span> ($blockContent <span class="hljs-keyword">as</span> $field =&gt; $value) {
                <span class="hljs-keyword">if</span> (is_array($value)) {
                    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($value[$locale]) || <span class="hljs-keyword">isset</span>($value[$fallbackLocale])) {
                        $blockContent[$field] = $block-&gt;translatedInput($field);
                    } <span class="hljs-keyword">else</span> {
                        <span class="hljs-keyword">foreach</span> (config(<span class="hljs-string">'translatable.locales'</span>) <span class="hljs-keyword">as</span> $allowedLocale) {
                            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($value[$allowedLocale])) {
                                $blockContent[$field] = <span class="hljs-literal">null</span>;
                                <span class="hljs-keyword">break</span>;
                            }
                        }
                    }
                }
            }
            $block-&gt;content = $blockContent;
        }

        <span class="hljs-keyword">return</span> $block-&gt;only(Arr::collapse(
            [
                [
                    <span class="hljs-string">'editor_name'</span>,
                    <span class="hljs-string">'position'</span>,
                    <span class="hljs-string">'type'</span>,
                    <span class="hljs-string">'content'</span>,
                ],
                ($block-&gt;childs &amp;&amp; count($block-&gt;childs) &gt; <span class="hljs-number">0</span>) ? [<span class="hljs-string">'childs'</span>] : []
            ]
        ));
    }
}
</code></pre>
<h3 id="heading-adaptations-of-the-model-of-our-module"><strong>Adaptations of the Model of our Module</strong></h3>
<p>It must now:</p>
<ul>
<li><p>extend our Base Model</p>
</li>
<li><p>declare the <code>blocks</code> attribute in its <code>$publicAttributes</code> array attribute</p>
</li>
</ul>
<p><strong>/app/Models/PageContent.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// use A17\Twill\Models\Model;</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Sortable</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">array</span> $publicAttributes = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
        <span class="hljs-string">'blocks'</span>,
    ];
}
</code></pre>
<h3 id="heading-adapt-our-existing-module-controllers"><strong>Adapt our existing Module controllers</strong></h3>
<p>On both Back and Frontend controllers for our Module, we will call the <code>computeBlocks()</code> method on the <code>$item</code>.</p>
<p><strong>/app/Http/Controllers/Admin/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

...

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    ...

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@param</span> Model $item
     * <span class="hljs-doctag">@return</span> array
     */</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">previewData</span>(<span class="hljs-params">$item</span>)
    </span>{

        $item-&gt;computeBlocks();


        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;previewForInertia($item-&gt;only($item-&gt;publicAttributes), [
            <span class="hljs-string">'page'</span> =&gt; <span class="hljs-string">'Page/Content'</span>,
        ]);
    }
}
</code></pre>
<p><strong>/app/Http/Controllers/App/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

...

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $slug</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        $item = Cache::rememberForever(
            <span class="hljs-string">'page.content.'</span> . app()-&gt;getLocale() . <span class="hljs-string">'.'</span> . $slug,
            <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) <span class="hljs-title">use</span> (<span class="hljs-params">$slug</span>) </span>{
                $item = PageContent::publishedInListings()
                    -&gt;forSlug($slug)
                    -&gt;first();
                <span class="hljs-keyword">if</span> ($item !== <span class="hljs-literal">null</span>) {
                    $item-&gt;load(<span class="hljs-string">'translations'</span>, <span class="hljs-string">'medias'</span>, <span class="hljs-string">'blocks'</span>);


                    $item-&gt;computeBlocks();


                }
                <span class="hljs-keyword">return</span> $item;
            }
        );

        ...
    }
}
</code></pre>
<p>Here is what we have now on the Vue side:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703070694430/6ae5aa15-d9b0-4374-9bc2-547a0060eb35.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>We could clean up more by removing <code>editor_name</code> and <code>position</code>, but we decided to keep them because it happens to us to have several BlockEditor fields on a same Module, and also to handle display behaviors depending on the position (for example, for our <code>Title</code> block, we could define an <code>h1</code> if position is 1 and an <code>h2</code> otherwise).</p>
</blockquote>
<h2 id="heading-vue-block-creation">Vue Block creation</h2>
<p>Now we have a clean and orderer array of blocks that we can process in ou Inertia Page as a Vue Single-File Component (SFC).</p>
<h3 id="heading-block-component">Block component</h3>
<p>We will create a Vue component that corresponds to the Twill Block.</p>
<p><strong>/resources/views/Components/Theme/Block/Common/Title.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'BlockCommonTitle'</span>,
})

interface Props {
  <span class="hljs-attr">block</span>: Model.Block &amp; PropsBlock
}

type PropsBlock = {
  <span class="hljs-attr">content</span>: {
    title?: string | <span class="hljs-literal">null</span>
  }
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.content?.title"</span>
    <span class="hljs-attr">v-html</span>=<span class="hljs-string">"block.content.title"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center text-4xl font-semibold text-gray-900"</span>
  &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h3 id="heading-typescript-types-enhancement-optional">TypeScript types enhancement [optional]</h3>
<p>We can create a <code>Block</code> type, and add <code>blocks</code> to our <code>Page</code> type:</p>
<p><strong>/resources/js/types/models.d.ts</strong></p>
<pre><code class="lang-javascript">declare namespace Model {
  <span class="hljs-keyword">export</span> type Page = {
    ...
    blocks?: <span class="hljs-built_in">Array</span>&lt;Block&gt; | <span class="hljs-literal">null</span>
  }

  <span class="hljs-keyword">export</span> type Block = {
    <span class="hljs-attr">editor_name</span>: string
    <span class="hljs-attr">position</span>: number
    <span class="hljs-attr">type</span>: string
    <span class="hljs-attr">content</span>: {} | <span class="hljs-literal">null</span>
  }
}
</code></pre>
<h3 id="heading-adding-a-block-alias-optional">Adding a <code>@Block</code> alias [optional]</h3>
<p><strong>/vite.config.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  <span class="hljs-attr">resolve</span>: {
    <span class="hljs-attr">alias</span>: [
      {
        <span class="hljs-attr">find</span>: <span class="hljs-string">'@Block'</span>,
        <span class="hljs-attr">replacement</span>: <span class="hljs-string">'/resources/views/Components/Theme/Block'</span>,
      },

      ...
    ],
  },
})
</code></pre>
<p><strong>/tsconfig.json</strong></p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"compilerOptions"</span>: {
    ...

    <span class="hljs-string">"paths"</span>: {
      <span class="hljs-string">"@Block/*"</span>: [<span class="hljs-string">"resources/views/Components/Theme/Blocks/*"</span>],

      ...
    },

    ...
  }
}
</code></pre>
<h2 id="heading-integration-into-our-inertia-vue-page">Integration into our Inertia Vue Page</h2>
<ul>
<li><p>We will load our blocks asynchronously, avoiding unnecessary component loading using <a target="_blank" href="https://vuejs.org/guide/components/async">Vue 3 <code>defineAsyncComponent()</code></a></p>
</li>
<li><p>In the template, if our <code>item</code> has blocks, we will loop through the list and load the appropriate Vue component based on its type value (<code>v-if="block.type == 'my-block-name'")</code></p>
</li>
</ul>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/Head.vue'</span>

interface Props {
  <span class="hljs-attr">item</span>: Model.Page
}

defineProps&lt;Props&gt;()

<span class="hljs-keyword">const</span> BlockCommonTitle = defineAsyncComponent(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'@Block/Common/Title.vue'</span>))
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">Head</span> <span class="hljs-attr">:item</span>=<span class="hljs-string">"item"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-if</span>=<span class="hljs-string">"item?.blocks &amp;&amp; Array.isArray(item.blocks) &amp;&amp; item.blocks.length &gt; 0"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto w-full max-w-6xl"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(block, index) in item.blocks"</span>
      <span class="hljs-attr">:key</span>=<span class="hljs-string">"index"</span>
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">BlockCommonTitle</span>
        <span class="hljs-attr">v-if</span>=<span class="hljs-string">"block.type == 'common-title'"</span>
        <span class="hljs-attr">:block</span>=<span class="hljs-string">"block"</span>
      &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">BlockCommonTitle</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<p>The rendering is as follows:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703076901807/3c85f4b3-b0c8-484e-9871-9b94583fb1d5.png" alt class="image--center mx-auto" /></p>
<hr />
<p><strong>We now have our first Block, we will see in a later article how to create other blocks with medias, links, HTML, ...</strong></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Laravel - Backup your filesystem disks]]></title><description><![CDATA[Learn how to efficiently back up your Laravel application's external disks using the powerful Laravel Backup package with a step-by-step guide]]></description><link>https://tech.codivores.com/laravel-backup-external-filesystem-disks</link><guid isPermaLink="true">https://tech.codivores.com/laravel-backup-external-filesystem-disks</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Backup]]></category><category><![CDATA[spatie]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 08 Jun 2023 08:48:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686036807580/7a66a772-6be2-4530-a877-fd1b757eada0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You are probably already familiar with the work of Spatie and its contributors in the Laravel and Open Source ecosystem.</p>
<p>For many years, we have been using their Backup package (<a target="_blank" href="https://spatie.be/docs/laravel-backup">https://spatie.be/docs/laravel-backup</a>) to back up our applications (databases and assets) on cloud provider's object storage like S3 or OpenStack Swift.</p>
<p>As our projects started utilizing more and more external disks to store assets and files generated by the application, such as PDF files, we encountered a limitation with the package — it only supports the backup of local files.</p>
<p>In this article, we will explore how to extend the package to back up external Laravel disks (S3 compatible, OpenStack Swift, ...).</p>
<h1 id="heading-deep-dive-into-the-package-code">Deep dive into the Package code</h1>
<p>Let's take a closer look at the code of the package. Upon inspection, we can understand why it only handles local files:</p>
<ul>
<li><p>it uses the <code>Symfony Finder</code> to locate the files to back up</p>
</li>
<li><p>it creates a <code>temporary local folder</code> to create a <code>Zip file</code> before sending it to the configured destination disks (after the backup process is complete, the temporary folder is deleted)</p>
</li>
</ul>
<p>Making the Symfony Finder work with other filesystem types would require significant effort, and downloading the content of external disks to create a Zip file locally, and then sending it to other disks, is not an ideal solution...</p>
<p>However, there is good news. The package dispatches several events, such as when the Zip file is created, when the backup fails or succeeds, ...</p>
<h1 id="heading-the-approach">The Approach</h1>
<p>Based on these observations, we can devise a strategy to back up our external disks:</p>
<ul>
<li><p>Instead of creating a Zip file, we will perform a direct copy of the files to the destination disks</p>
</li>
<li><p>We will listen to the following events to trigger our custom processes:</p>
<ul>
<li><p><strong>BackupWasSuccessful</strong>: to launch the copy operation</p>
</li>
<li><p><strong>CleanupWasSuccessful</strong>: to clean up old backups</p>
</li>
</ul>
</li>
</ul>
<h1 id="heading-implementation">Implementation</h1>
<h2 id="heading-configuration">Configuration</h2>
<p>First, let's add a new entry in the package's configuration file to specify the disks we want to back up.</p>
<p><strong>/config/backup.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">return</span> [
    <span class="hljs-string">'backup'</span> =&gt; [
        <span class="hljs-string">'source'</span> =&gt; [
            <span class="hljs-comment">// ...</span>
            <span class="hljs-string">'disks'</span> =&gt; [
                <span class="hljs-string">'assets'</span>,
                <span class="hljs-string">'customers'</span>,
            ],
            <span class="hljs-comment">// ...</span>
        ],
];
</code></pre>
<h2 id="heading-the-logic">The logic</h2>
<p>We will create a Subscriber to handle the events and implement our custom processes.</p>
<h3 id="heading-backupwassuccessful-event">BackupWasSuccessful event</h3>
<p>The <code>BackupWasSuccessful</code> event is the most suitable event to perform our custom copy operation. It is dispatched when the standard backup job has finished its work.</p>
<p>By accessing the <code>backupDestination</code> instance provided by the event, we can obtain the path of the Zip file on the destination disk.</p>
<p>Here's how we proceed:</p>
<ul>
<li><p>we compute the backup path. To simplify backup and cleanup,</p>
<ul>
<li>the directory that will be created will have the same name as the Zip file</li>
</ul>
</li>
</ul>
<p>    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686213827566/3da0eeaa-b630-4c07-8774-c1ae57b4b64f.png" alt class="image--right mx-auto mr-0" /></p>
<ul>
<li>the files / directories will be copied into a subdirectory that will have the same name as the external disk (here we back up two disks: assets and customers)</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686213770139/c94cb667-755e-4ba4-8b94-320a25d2b920.png" alt class="image--right mx-auto mr-0" /></p>
<ul>
<li><p>we retrieve all the external disks we want to back up from the package's configuration file, and for each disk:</p>
<ul>
<li><p>we retrieve all the files, including subdirectories.</p>
</li>
<li><p>we copy each file to the backup disk configured in the package.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-cleanupwassuccessful-event">CleanupWasSuccessful event</h3>
<p>The <code>CleanupWasSuccessful</code> event is the most suitable event to perform our custom cleanup. It is dispatched when the standard cleanup job has finished its work.</p>
<p>Similar to the previous event, we can access the <code>backupDestination</code> instance provided by the event.</p>
<p>Here's how we proceed:</p>
<ul>
<li><p>we retrieve all the directories on the destination disk. These directories are expected to contain only the custom backups<br />  ❗All directories not related to backups in the backup directory will be deleted</p>
</li>
<li><p>we retrieve all of the existing Zip backups from the <code>backupDestination</code> (we add <code>fresh()</code> method call because the Job removes the last backup from the collection, and as it's cached, we need to retrieve the updated list)</p>
</li>
<li><p>we compute the directories to delete by identifying the directories that do not have a corresponding Zip file.</p>
</li>
<li><p>we delete the directories that need to be cleaned up</p>
</li>
</ul>
<h2 id="heading-subscriber-code">Subscriber code</h2>
<p><strong>/app/Listeners/BackupEventSubscriber.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Listeners</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Events</span>\<span class="hljs-title">Dispatcher</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Storage</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Str</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span>\<span class="hljs-title">Backup</span>\<span class="hljs-title">Events</span>\<span class="hljs-title">BackupWasSuccessful</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Spatie</span>\<span class="hljs-title">Backup</span>\<span class="hljs-title">Events</span>\<span class="hljs-title">CleanupWasSuccessful</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Symfony</span>\<span class="hljs-title">Component</span>\<span class="hljs-title">Console</span>\<span class="hljs-title">Output</span>\<span class="hljs-title">ConsoleOutput</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BackupEventSubscriber</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">subscribe</span>(<span class="hljs-params">Dispatcher $events</span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            BackupWasSuccessful::class =&gt; <span class="hljs-string">'handleBackup'</span>,
            CleanupWasSuccessful::class =&gt; <span class="hljs-string">'handleCleanup'</span>,
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleBackup</span>(<span class="hljs-params">BackupWasSuccessful $event</span>): <span class="hljs-title">void</span>
    </span>{
        $backupDestination = $event-&gt;backupDestination;
        $backupPath = Str::replaceLast(<span class="hljs-string">'.zip'</span>, <span class="hljs-string">''</span>, $backupDestination-&gt;newestBackup()-&gt;path());

        $output = <span class="hljs-keyword">new</span> ConsoleOutput();

        $sources = config(<span class="hljs-string">'backup.backup.source.disks'</span>) ?? [];

        <span class="hljs-keyword">foreach</span> ($sources <span class="hljs-keyword">as</span> $disk) {
            $output-&gt;writeln(<span class="hljs-string">'&lt;info&gt;Determining files to backup for disk '</span> . $disk . <span class="hljs-string">'...&lt;/info&gt;'</span>);
            $destinationPath = $backupPath . <span class="hljs-string">'/'</span> . $disk . <span class="hljs-string">'/'</span>;

            $files = Storage::disk($disk)-&gt;allFiles();
            $output-&gt;writeln(<span class="hljs-string">'&lt;info&gt;Copying disk '</span> . $disk . <span class="hljs-string">' to disk named backup: '</span> . count($files) . <span class="hljs-string">' files&lt;/info&gt;'</span>);

            <span class="hljs-keyword">foreach</span> ($files <span class="hljs-keyword">as</span> $file) {
                Storage::disk($backupDestination-&gt;diskName())-&gt;put(
                    $destinationPath . $file,
                    Storage::disk($disk)-&gt;get($file)
                );
            }
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleCleanup</span>(<span class="hljs-params">CleanupWasSuccessful $event</span>): <span class="hljs-title">void</span>
    </span>{
        $backupDestination = $event-&gt;backupDestination;

        $output = <span class="hljs-keyword">new</span> ConsoleOutput();
        $output-&gt;writeln(<span class="hljs-string">'&lt;info&gt;Cleaning disks backups of '</span> . $backupDestination-&gt;backupName() . <span class="hljs-string">' on disk '</span> . $backupDestination-&gt;diskName() . <span class="hljs-string">'...&lt;/info&gt;'</span>);

        $directories = Storage::disk($backupDestination-&gt;diskName())-&gt;directories($backupDestination-&gt;backupName());

        <span class="hljs-keyword">if</span> (count($directories) &gt; <span class="hljs-number">0</span>) {
            $backups = $backupDestination
                -&gt;fresh()
                -&gt;backups()
                -&gt;map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$backup</span>) </span>{
                    <span class="hljs-keyword">return</span> Str::replaceLast(<span class="hljs-string">'.zip'</span>, <span class="hljs-string">''</span>, $backup-&gt;path());
                })
                -&gt;toArray();

            $directoriesToDelete = array_filter($directories, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$directory</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$backups</span>) </span>{
                <span class="hljs-keyword">return</span> !in_array($directory, $backups);
            });

            <span class="hljs-keyword">if</span> (count($directoriesToDelete) &gt; <span class="hljs-number">0</span>) {
                <span class="hljs-keyword">foreach</span> ($directoriesToDelete <span class="hljs-keyword">as</span> $directory) {
                    Storage::disk($backupDestination-&gt;diskName())-&gt;deleteDirectory($directory);
                }
            }
        }
    }
}
</code></pre>
<h2 id="heading-register-the-subscriber">Register the Subscriber</h2>
<p>The final step is to register the Subscriber in the Laravel <code>EventServiceProvider</code></p>
<p><strong>/app/Providers/EventServiceProvider.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Providers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Listeners</span>\<span class="hljs-title">BackupEventSubscriber</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Providers</span>\<span class="hljs-title">EventServiceProvider</span> <span class="hljs-title">as</span> <span class="hljs-title">ServiceProvider</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EventServiceProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ServiceProvider</span>
</span>{
    <span class="hljs-comment">/**
     * The subscriber classes to register.
     *
     * <span class="hljs-doctag">@var</span> array
     */</span>
    <span class="hljs-keyword">protected</span> $subscribe = [
        BackupEventSubscriber::class,
    ];
}
</code></pre>
<hr />
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://media.giphy.com/media/26Ffd0AF5J2kJgWhG/giphy.gif">https://media.giphy.com/media/26Ffd0AF5J2kJgWhG/giphy.gif</a></div>
]]></content:encoded></item><item><title><![CDATA[Twill preview with Inertia]]></title><description><![CDATA[Deep dive into Twill, a CMS package for Laravel, and preview your content in an Inertia page in your admin]]></description><link>https://tech.codivores.com/ltivt-9-laravel-twill-preview-with-inertia</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-9-laravel-twill-preview-with-inertia</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Twill]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Mon, 05 Jun 2023 09:05:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685630161377/cee34abe-e15b-4395-a75f-b39431e40c8e.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If a Twill module uses Revisions, you can benefit from an awesome Twill feature: preview your changes before publishing and compare old revisions. By default, it uses Blade views, so working with Inertia needs some adjustments.</p>
<h2 id="heading-the-principle">The principle</h2>
<p>For now, Inertia pages cannot be rendered in an iframe through <code>srcdoc</code> attribute (that is the way Twill manages the preview): <a target="_blank" href="https://github.com/inertiajs/inertia/issues/1008">https://github.com/inertiajs/inertia/issues/1008</a>.</p>
<p>We need to implement a workaround to get our Inertia pages rendered by the Twill Blade view:</p>
<ol>
<li><p>Prepare the data for Twill <code>preview()</code> method in our Module Controller</p>
</li>
<li><p>Render the Twill preview Blade view that will redirect to a custom PreviewController</p>
</li>
<li><p>Retrieve and bind the data in the PreviewController to render the requested Inertia page</p>
</li>
</ol>
<h2 id="heading-prepare-the-data-for-the-blade-view">Prepare the data for the Blade view</h2>
<p>The aim is to</p>
<ul>
<li><p>put all the needed data in session with a specific key</p>
</li>
<li><p>provide to the Blade view this session key and the route to the PreviewController</p>
</li>
</ul>
<p>To achieve this, we will create a Trait with our custom logic and use it in our Module controllers.</p>
<h3 id="heading-trait-creation-to-prepare-the-data">Trait creation to prepare the data</h3>
<p><strong>/app/Http/Controllers/Twill/Traits/HasPreview.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Traits</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Str</span>;

<span class="hljs-keyword">trait</span> HasPreview
{
    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">previewForInertia</span>(<span class="hljs-params">$item, <span class="hljs-keyword">array</span> $config</span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-comment">// Session reflash is needed for revisions comparison.</span>
        request()-&gt;session()-&gt;reflash();

        <span class="hljs-keyword">if</span> (in_array(<span class="hljs-string">'blocks'</span>, $config)) {
            $item-&gt;computeBlocks();
        }

        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($config[<span class="hljs-string">'medias'</span>]) &amp;&amp; is_array($config[<span class="hljs-string">'medias'</span>])) {
            <span class="hljs-keyword">foreach</span> ($config[<span class="hljs-string">'medias'</span>] <span class="hljs-keyword">as</span> $role) {
                $item-&gt;computeMedias($role);
            }
        }

        $sessionKey = <span class="hljs-string">'adminPreview_'</span> . Str::random(<span class="hljs-number">40</span>);

        request()-&gt;session()-&gt;flash($sessionKey, [
            <span class="hljs-string">'module'</span> =&gt; Str::singular(<span class="hljs-keyword">$this</span>-&gt;moduleName),
            <span class="hljs-string">'page'</span> =&gt; $config[<span class="hljs-string">'page'</span>] ?? <span class="hljs-literal">null</span>,
            <span class="hljs-string">'itemPreview'</span> =&gt; $item,
            <span class="hljs-string">'props'</span> =&gt; $config[<span class="hljs-string">'props'</span>] ?? [],
        ]);

        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'route'</span> =&gt; route(<span class="hljs-string">'twill.preview'</span>),
            <span class="hljs-string">'sessionKey'</span> =&gt; $sessionKey,
        ];
    }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Computes <code>blocks</code> and <code>medias</code> of the item for Inertia rendering (we will see this part in detail in a further article).</p>
</li>
<li><p>Puts in session:</p>
<ul>
<li><p>the module's singular name in <code>module</code></p>
</li>
<li><p>the Inertia page to render in <code>page</code></p>
</li>
<li><p>the Model item mapped to <code>itemPreview</code></p>
</li>
<li><p>the potential additional <code>props</code> that will be injected into the Inertia page</p>
</li>
</ul>
</li>
<li><p>Gives the Twill <code>preview()</code> method:</p>
<ul>
<li><p>the <code>route</code> to the PreviewController</p>
</li>
<li><p>the <code>sessionKey</code> to retrieve our data</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-using-the-trait-in-our-module-controller">Using the Trait in our Module controller</h3>
<p><strong>/app/Http/Controllers/Admin/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Traits</span>\<span class="hljs-title">HasPreview</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillModuleController</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasPreview</span>;

    <span class="hljs-keyword">protected</span> $previewView = <span class="hljs-string">'twill.preview'</span>;

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">previewData</span>(<span class="hljs-params">$item</span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;previewForInertia($item-&gt;only($item-&gt;publicAttributes), [
            <span class="hljs-string">'page'</span> =&gt; <span class="hljs-string">'Page/Content'</span>,
        ]);
    }
}
</code></pre>
<h2 id="heading-create-the-preview-blade-view">Create the preview Blade view</h2>
<p><strong>/resources/views/twill/preview.blade.php</strong></p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0, maximum-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onload</span>=<span class="hljs-string">"window.location='{{ $route }}?sessionKey={{ $sessionKey }}'"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-render-the-inertia-page-through-the-previewcontroller">Render the Inertia page through the PreviewController</h2>
<h3 id="heading-route">Route</h3>
<p><strong>/routes/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">PreviewController</span>;

Route::get(<span class="hljs-string">'preview'</span>, PreviewController::class)-&gt;name(<span class="hljs-string">'preview'</span>);
...
</code></pre>
<h3 id="heading-controller">Controller</h3>
<p><strong>/app/Http/Controllers/Twill/Base/PreviewController.php</strong></p>
<pre><code class="lang-php">@@ <span class="hljs-number">-0</span>,<span class="hljs-number">0</span> +<span class="hljs-number">1</span>,<span class="hljs-number">47</span> @@
<span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">Controller</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">ModuleController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Application</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Request</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PreviewController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ModuleController</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">Application $app, Request $request</span>)
    </span>{
        Controller::__construct($app, $request);
        <span class="hljs-keyword">$this</span>-&gt;app = $app;
        <span class="hljs-keyword">$this</span>-&gt;request = $request;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke</span>(<span class="hljs-params">Request $request</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        <span class="hljs-comment">// Session reflash is needed for revisions comparison.</span>
        $request-&gt;session()-&gt;reflash();

        abort_if(!$request-&gt;has(<span class="hljs-string">'sessionKey'</span>), Response::HTTP_NOT_FOUND);

        $sessionKey = $request-&gt;input(<span class="hljs-string">'sessionKey'</span>);

        abort_if(!$request-&gt;session()-&gt;has($sessionKey), Response::HTTP_NOT_FOUND);

        $input = $request-&gt;session()-&gt;get($sessionKey);

        abort_if(!<span class="hljs-keyword">isset</span>($input[<span class="hljs-string">'module'</span>]) || !<span class="hljs-keyword">isset</span>($input[<span class="hljs-string">'itemPreview'</span>]), Response::HTTP_NOT_FOUND);

        $item = $input[<span class="hljs-string">'itemPreview'</span>];

        $props = $input[<span class="hljs-string">'props'</span>] ?? [];
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">isset</span>($props[<span class="hljs-string">'locale'</span>])) {
            $props[<span class="hljs-string">'locale'</span>] = app()-&gt;getLocale();
        }

        $page = $input[<span class="hljs-string">'page'</span>] ?? ucfirst($input[<span class="hljs-string">'module'</span>]) . <span class="hljs-string">'/Item'</span>;

        <span class="hljs-keyword">return</span> match ($input[<span class="hljs-string">'module'</span>]) {
            <span class="hljs-keyword">default</span> =&gt; Inertia::render($page, [<span class="hljs-string">'item'</span> =&gt; $item] + $props),
        };
    }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Checks if the <code>sessionKey</code> is provided in the request</p>
</li>
<li><p>Checks if the session exists and has the required data</p>
</li>
<li><p>Retrieves the props and adds the <code>locale</code> props</p>
</li>
<li><p>Computes the Inertia page to render.<br />  If the page is not set in your <code>previewData()</code> data, it uses the <code>Item.vue</code> SFC located in the <code>ModuleName</code> directory (for example, for a <code>Projects</code> Twill module, it will look for <code>/resources/views/Pages/Project/Item.vue</code>)</p>
</li>
<li><p>Renders the Inertia page with the provided props (we use a <code>match()</code> on the module name as we may have specific logic for some modules)</p>
</li>
</ul>
<h2 id="heading-improvement">Improvement</h2>
<p>We can create our base Twill controllers (for Module and Singleton) that use the Trait and define the previewView and make our controllers extend those to avoid defining everything in every Module controller that needs preview.</p>
<p>To do so, we need base controllers to extend the:</p>
<ul>
<li><p>Twill Module controller</p>
</li>
<li><p>Twill Singleton Module controller</p>
</li>
</ul>
<h3 id="heading-create-base-controllers-in-the-application">Create Base controllers in the application</h3>
<p><strong>/app/Http/Controllers/Admin/Base/ModuleController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">ModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">TwillModuleController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Traits</span>\<span class="hljs-title">HasPreview</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ModuleController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillModuleController</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasPreview</span>;

    <span class="hljs-keyword">protected</span> $previewView = <span class="hljs-string">'twill.preview'</span>;
}
</code></pre>
<p><strong>/app/Http/Controllers/Admin/Base/SingletonModuleController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">SingletonModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">TwillSingletonModuleController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Traits</span>\<span class="hljs-title">HasPreview</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SingletonModuleController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TwillSingletonModuleController</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasPreview</span>;

    <span class="hljs-keyword">protected</span> $previewView = <span class="hljs-string">'twill.preview'</span>;
}
</code></pre>
<h3 id="heading-adapt-our-existing-module-controllers">Adapt our existing Module controllers</h3>
<p><strong>/app/Http/Controllers/Admin/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// use A17\Twill\Http\Controllers\Admin\ModuleController as BaseModuleController;</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">ModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseModuleController</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">previewData</span>(<span class="hljs-params">$item</span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;previewForInertia($item-&gt;only($item-&gt;publicAttributes), [
            <span class="hljs-string">'page'</span> =&gt; <span class="hljs-string">'Page/Content'</span>,
        ]);
    }
}
</code></pre>
<p><strong>/app/Http/Controllers/Admin/PageHomeController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// use A17\Twill\Http\Controllers\Admin\SingletonModuleController as BaseModuleController;</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Base</span>\<span class="hljs-title">SingletonModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseModuleController</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageHomeController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">previewData</span>(<span class="hljs-params">$item</span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;previewForInertia($item-&gt;only($item-&gt;publicAttributes), [
            <span class="hljs-string">'page'</span> =&gt; <span class="hljs-string">'Page/Home'</span>,
        ]);
    }
}
</code></pre>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Homepage singleton module]]></title><description><![CDATA[Deep dive into Twill, a CMS package for Laravel, and build with us your homepage]]></description><link>https://tech.codivores.com/ltivt-8-laravel-twill-homepage-module</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-8-laravel-twill-homepage-module</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Twill]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Sun, 04 Jun 2023 09:05:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685614464418/caa0b14f-3080-456d-9e5b-7075ccd270e9.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will see the creation and customization of a Twill singleton module to provide a Homepage for our application.</p>
<h2 id="heading-singleton-module-creation">Singleton module creation</h2>
<p>In Twill terminology, a Singleton Module is globally like a classic module except that it manages only one Model.</p>
<p>The main differences:</p>
<ul>
<li><p>No need to handle a listing page</p>
</li>
<li><p>No need to provide create, delete, and probably publish features</p>
</li>
<li><p>Creation of a seeder to create the Model in the database</p>
</li>
</ul>
<h3 id="heading-generation">Generation</h3>
<p>A Singleton Module can be initiated with the CLI generator:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># PageHome module with Blocks, Translation, Revisions</span>
php artisan twill:make:singleton PageHome -BTR
</code></pre>
<p>The output we can see in our terminal:</p>
<pre><code class="lang-php">Migration created successfully! Add some fields!
Models created successfully! Fill your fillables!
Repository created successfully! Control all the things!
Controller created successfully! Define your index/browser/form endpoints options!
Form request created successfully! Add some validation rules!

 <span class="hljs-keyword">Do</span> you also want to generate the preview file? [no]:
  [<span class="hljs-number">0</span>] no
  [<span class="hljs-number">1</span>] yes
 &gt; 

Seed created successfully!
The following snippet has been added to routes/twill.php:
-----
TwillRoutes::singleton(<span class="hljs-string">'pageHome'</span>);
-----
To add a navigation entry add the following to your AppServiceProvider BOOT method.
-----
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillNavigation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Navigation</span>\<span class="hljs-title">NavigationLink</span>;
TwillNavigation::addLink(
    NavigationLink::make()-&gt;forSingleton(<span class="hljs-string">'pageHome'</span>)
);
-----
Migrate your database &amp; seed your singleton module:

    php artisan migrate

    php artisan db:seed PageHomeSeeder

Enjoy.
</code></pre>
<h3 id="heading-files-generated">Files generated</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685614167741/e101e25d-34fc-420d-8dee-fc95368d3598.png" alt /></p>
<h3 id="heading-what-next">What next</h3>
<ul>
<li><p>Edit the Routes and create a Navigation entry</p>
</li>
<li><p>Customize the fields of the Model</p>
</li>
<li><p>Customize the admin Controller setup, form</p>
</li>
<li><p>Morph map</p>
</li>
<li><p>Seed the Model</p>
</li>
<li><p>Initiate the front-end: Controller, Route, Page</p>
</li>
</ul>
<h2 id="heading-twill-module-customization">Twill module customization</h2>
<h3 id="heading-routes-and-navigation">Routes and Navigation</h3>
<p><strong>Routes configuration</strong></p>
<p><strong>/routes/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillRoutes</span>;

TwillRoutes::singleton(<span class="hljs-string">'pageHome'</span>);
</code></pre>
<p><strong>Navigation entry</strong></p>
<p>We add a NavigationLink as a sibling of our previous <code>PageContent</code> module.</p>
<p><strong>/app/Providers/AppServiceProvider.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Providers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillNavigation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Navigation</span>\<span class="hljs-title">NavigationLink</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppServiceProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ServiceProvider</span>
</span>{
    <span class="hljs-comment">/**
     * Bootstrap any application services.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        TwillNavigation::addLink(
            NavigationLink::make()
                ...
                -&gt;setChildren([
                    NavigationLink::make()
                        -&gt;title(Str::ucfirst(__(<span class="hljs-string">'home'</span>)))
                        -&gt;forSingleton(<span class="hljs-string">'pageHome'</span>),
                    ...
                ]),
        );
    }
}
</code></pre>
<h3 id="heading-model">Model</h3>
<p>In our case, we want:</p>
<ul>
<li><p>to remove the default published attribute (our homepage will always be published)</p>
</li>
<li><p>a title that can be translated</p>
</li>
<li><p>meta title and description that can be translated</p>
</li>
<li><p>a block editor for all the content (we will focus on this part in a later article)</p>
</li>
</ul>
<p><strong>/database/migrations/..._create_page_homes_tables.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Migrations</span>\<span class="hljs-title">Migration</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Schema</span>\<span class="hljs-title">Blueprint</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Schema</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreatePageHomesTables</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::create(<span class="hljs-string">'page_homes'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultTableFields($table, <span class="hljs-literal">true</span>, <span class="hljs-literal">false</span>);
        });

        Schema::create(<span class="hljs-string">'page_home_translations'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultTranslationsTableFields($table, <span class="hljs-string">'page_home'</span>);
        });

        Schema::table(<span class="hljs-string">'page_home_translations'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;after(<span class="hljs-string">'page_home_id'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$table</span>) </span>{
                $table-&gt;string(<span class="hljs-string">'title'</span>, <span class="hljs-number">200</span>)-&gt;nullable();
                $table-&gt;string(<span class="hljs-string">'meta_title'</span>, <span class="hljs-number">100</span>)-&gt;nullable();
                $table-&gt;text(<span class="hljs-string">'meta_description'</span>, <span class="hljs-number">200</span>)-&gt;nullable();
            });
        });

        Schema::create(<span class="hljs-string">'page_home_revisions'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultRevisionsTableFields($table, <span class="hljs-string">'page_home'</span>);
        });
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::dropIfExists(<span class="hljs-string">'page_home_revisions'</span>);
        Schema::dropIfExists(<span class="hljs-string">'page_home_translations'</span>);
        Schema::dropIfExists(<span class="hljs-string">'page_homes'</span>);
    }
}
</code></pre>
<blockquote>
<p>To remove the <code>published</code> attribute, you have to set the third parameter of <code>createDefaultTableFields()</code> method to <code>false</code>.</p>
</blockquote>
<p>We can now run our migration to create the tables for our Module:</p>
<pre><code class="lang-bash">php artisan migrate
</code></pre>
<p><strong>/app/Models/PageHome.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Behaviors</span>\<span class="hljs-title">HasBlocks</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Behaviors</span>\<span class="hljs-title">HasTranslation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Behaviors</span>\<span class="hljs-title">HasRevisions</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageHome</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasBlocks</span>, <span class="hljs-title">HasTranslation</span>, <span class="hljs-title">HasRevisions</span>;

    <span class="hljs-keyword">protected</span> $fillable = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
    ];

    <span class="hljs-keyword">public</span> $translatedAttributes = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
        <span class="hljs-string">'active'</span>,
    ];

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">array</span> $publicAttributes = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
    ];
}
</code></pre>
<h3 id="heading-controller">Controller</h3>
<p>In our case, we want to:</p>
<ul>
<li><p>disable permalink, create, delete, publish and editor features (<a target="_blank" href="https://twillcms.com/docs/modules/controllers.html#content-disable-defaults">https://twillcms.com/docs/modules/controllers.html#content-disable-defaults</a>)</p>
</li>
<li><p>configure the form:</p>
<ul>
<li><p>a block editor for all the content</p>
</li>
<li><p>meta title and description that can be translated in the sidebar</p>
</li>
</ul>
</li>
</ul>
<p><strong>/app/Http/Controllers/Twill/PageHomeController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">TwillModelContract</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">SingletonModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseModuleController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">BlockEditor</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fieldset</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageHomeController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    <span class="hljs-keyword">protected</span> $moduleName = <span class="hljs-string">'pageHomes'</span>;

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setUpController</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;disablePermalink();
        <span class="hljs-keyword">$this</span>-&gt;disableCreate();
        <span class="hljs-keyword">$this</span>-&gt;disableDelete();
        <span class="hljs-keyword">$this</span>-&gt;disablePublish();
        <span class="hljs-keyword">$this</span>-&gt;disableEditor();
    }

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formData</span>(<span class="hljs-params">$request</span>)
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'customPermalink'</span> =&gt; route(<span class="hljs-string">'home'</span>),
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params">TwillModelContract $model</span>): <span class="hljs-title">Form</span>
    </span>{
        $form = <span class="hljs-built_in">parent</span>::getForm($model);

        $form-&gt;add(
            BlockEditor::make()
                -&gt;withoutSeparator()
        );

        <span class="hljs-keyword">return</span> $form;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSideFieldsets</span>(<span class="hljs-params">TwillModelContract $model</span>): <span class="hljs-title">Form</span>
    </span>{
        $form = <span class="hljs-built_in">parent</span>::getSideFieldsets($model);

        $form-&gt;addFieldset(
            Fieldset::make()
                -&gt;title(<span class="hljs-string">'SEO'</span>)
                -&gt;id(<span class="hljs-string">'seo'</span>)
                -&gt;fields([
                    Input::make()
                        -&gt;name(<span class="hljs-string">'meta_title'</span>)
                        -&gt;label(<span class="hljs-string">'Title'</span>)
                        -&gt;translatable()
                        -&gt;maxLength(<span class="hljs-number">100</span>),

                    Input::make()
                        -&gt;name(<span class="hljs-string">'meta_description'</span>)
                        -&gt;label(<span class="hljs-string">'Description'</span>)
                        -&gt;translatable()
                        -&gt;maxLength(<span class="hljs-number">200</span>),
                ])
        );

        <span class="hljs-keyword">return</span> $form;
    }
}
</code></pre>
<h3 id="heading-morph-map">Morph map</h3>
<p><strong>/app/Providers/AppServiceProvider.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Providers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Relations</span>\<span class="hljs-title">Relation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppServiceProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ServiceProvider</span>
</span>{
    <span class="hljs-comment">/**
     * Bootstrap any application services.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        Relation::enforceMorphMap([
            ...
            <span class="hljs-string">'pageHome'</span> =&gt; <span class="hljs-string">'App\Models\PageHome'</span>,
        ]);
    }
}
</code></pre>
<h3 id="heading-seeding">Seeding</h3>
<p>By default, Twill will automatically run the seeder when you visit the admin edition page (managed by the configuration value <code>twill.auto_seed_singletons</code>).</p>
<p>But you can manually run the Laravel <code>db:seed</code> command:</p>
<pre><code class="lang-bash">php artisan db:seed PageHomeSeeder
</code></pre>
<h2 id="heading-front-end-with-inertia">Front-end with Inertia</h2>
<p>This module aims to display a homepage on our front-end. To do so, we need:</p>
<ul>
<li><p>a Laravel Route</p>
</li>
<li><p>a Laravel Controller</p>
</li>
<li><p>an Inertia Page</p>
</li>
</ul>
<h3 id="heading-route">Route</h3>
<p><strong>/routes/web.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>\<span class="hljs-title">PageHomeController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;

Route::get(<span class="hljs-string">'/'</span>, PageHomeController::class)-&gt;name(<span class="hljs-string">'home'</span>);
</code></pre>
<h3 id="heading-controller-1">Controller</h3>
<p><strong>/app/Http/Controllers/App/PageHomeController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">PageHome</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Cache</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageHomeController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke</span>(<span class="hljs-params"></span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        $locale = app()-&gt;getLocale();

        $item = Cache::rememberForever(
            <span class="hljs-string">'page.home.'</span> . $locale,
            <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
                $item = PageHome::first();

                <span class="hljs-keyword">if</span> ($item !== <span class="hljs-literal">null</span>) {
                    $item-&gt;load(<span class="hljs-string">'translations'</span>, <span class="hljs-string">'blocks'</span>);
                }

                <span class="hljs-keyword">return</span> $item;
            }
        );

        abort_if($item === <span class="hljs-literal">null</span>, Response::HTTP_NOT_FOUND);

        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Page/Home'</span>, [
            <span class="hljs-string">'item'</span> =&gt; $item-&gt;only($item-&gt;publicAttributes),
            <span class="hljs-string">'locale'</span> =&gt; $locale,
        ]);
    }
}
</code></pre>
<h3 id="heading-page">Page</h3>
<p><strong>/resources/views/Pages/Page/Home.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/Head.vue'</span>

defineOptions({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'PageHome'</span>,
})

interface Props {
  <span class="hljs-attr">item</span>: Model.Page
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">Head</span> <span class="hljs-attr">:item</span>=<span class="hljs-string">"item"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center text-4xl font-semibold text-gray-900"</span>&gt;</span>
    {{ item.title }}
  <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<h2 id="heading-final-result">Final result</h2>
<p>You can now click on the permalink to open the front-end page in a new tab:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685626095394/233eefb3-25e2-4cb9-a1a6-676a48140985.png" alt class="image--center mx-auto" /></p>
<p>and you should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685626439455/0066d912-2212-4650-a8ae-8cb1b748653a.png" alt class="image--center mx-auto" /></p>
<hr />
<p><strong>We now have a singleton module to handle the homepage, we will see in later articles how to improve logic, performance and handle more complex content structure with blocks</strong></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Application level improvements]]></title><description><![CDATA[Improve your application structure using layouts, global head component]]></description><link>https://tech.codivores.com/ltivt-7-application-level-improvements</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-7-application-level-improvements</guid><category><![CDATA[Inertia.js]]></category><category><![CDATA[Twill]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Mon, 17 Apr 2023 10:47:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681665253746/8a644a6b-bcaf-4ca9-9d08-91609d0698ea.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-layouts">Layouts</h2>
<p>For the moment, we have just one Twill module with one Inertia page, but we will probably have more page templates with different modules in our application (home, blog, portfolio, contact, customer account, ...).</p>
<p>It may be a good idea to create one (or more) layouts that will be used by our different pages and will be persistent (not destroyed and recreated every visit). For this article, we will create 2 layouts and see how to use it on our pages:</p>
<ul>
<li><p>a Default for the common pages (which may have a header with a menu, a footer, ...)</p>
</li>
<li><p>a FullPage for custom pages (like authentication)</p>
</li>
</ul>
<h3 id="heading-layouts-creation">Layouts creation</h3>
<p>We create our 2 templates in a new directory <code>/resources/views/Components/Layout</code>:</p>
<p><strong>/resources/views/Components/Layout/Default.vue</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"min-h-full"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-white shadow"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-7xl px-4 py-6"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-3xl font-bold tracking-tight text-gray-900"</span>&gt;</span>My Application<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-7xl py-6"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<p><strong>/resources/views/Components/Layout/FullPage.vue</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"w-full flex flex-col h-screen content-center justify-center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<h3 id="heading-configuration">Configuration</h3>
<p>For the moment, our layouts are just Vue components, to make Inertia aware of the layout every page has to load, we need to do some changes in our application entry point in the <code>resolve()</code> method:</p>
<p><strong>/resources/js/app.ts</strong></p>
<p><strong>before:</strong></p>
<pre><code class="lang-typescript">  resolve: <span class="hljs-keyword">async</span> (name: <span class="hljs-built_in">string</span>) =&gt; {
    <span class="hljs-keyword">let</span> page = <span class="hljs-keyword">await</span> resolvePageComponent(<span class="hljs-string">`../views/Pages/<span class="hljs-subst">${name}</span>.vue`</span>, <span class="hljs-keyword">import</span>.meta.glob&lt;DefineComponent&gt;(<span class="hljs-string">'../views/Pages/**/*.vue'</span>))

    <span class="hljs-keyword">return</span> page
  },
</code></pre>
<p><strong>after:</strong></p>
<pre><code class="lang-typescript">  resolve: <span class="hljs-keyword">async</span> (name: <span class="hljs-built_in">string</span>) =&gt; {
    <span class="hljs-keyword">let</span> page = <span class="hljs-keyword">await</span> resolvePageComponent(<span class="hljs-string">`../views/Pages/<span class="hljs-subst">${name}</span>.vue`</span>, <span class="hljs-keyword">import</span>.meta.glob&lt;DefineComponent&gt;(<span class="hljs-string">'../views/Pages/**/*.vue'</span>))

    page = page.default

    page.layout = (<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">`../views/Components/Layout/<span class="hljs-subst">${page.layoutName || <span class="hljs-string">'Default'</span>}</span>.vue`</span>)).default

    <span class="hljs-keyword">return</span> page
  },
</code></pre>
<p><strong>What it does</strong></p>
<p>To set the <code>page.layout</code> value, it will</p>
<ul>
<li><p>look if the page has a <code>layoutName</code> option defined and then load the Component with that name which would be in <code>/resources/views/Components/Layout</code> directory</p>
</li>
<li><p>if not, load the <code>Default</code> layout</p>
</li>
</ul>
<p>More info in the <a target="_blank" href="https://inertiajs.com/pages#creating-layouts">official documentation</a>.</p>
<blockquote>
<p>We don't test if the layout Component file exists, if a wrong name is defined, it will trigger an error:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681721891269/63c78f7e-e8c8-4f70-acc7-8a723e04561a.png" alt /></p>
</blockquote>
<h3 id="heading-define-the-layout-of-the-page">Define the Layout of the page</h3>
<p>Now we can choose our layout on each page.</p>
<p>If you use the <code>unplugin-vue-define-options</code> plugin, it can be done like that:</p>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  <span class="hljs-attr">layoutName</span>: <span class="hljs-string">'FullPage'</span>,
})

interface Props {
  <span class="hljs-attr">item</span>: Model.Page
  <span class="hljs-attr">locale</span>: string
}

defineProps&lt;Props&gt;()
&lt;/script&gt;
</code></pre>
<p>If not, we need to use Option API like that:</p>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript">&lt;script lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">layoutName</span>: <span class="hljs-string">'FullPage'</span>,
}
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span>&gt;</span><span class="xml">
interface Props {
  item: Model.Page
  locale: string
}

defineProps<span class="hljs-tag">&lt;<span class="hljs-name">Props</span>&gt;</span>()
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>You should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681722777316/5a7e0239-4c06-4c09-8ef8-34ea1e229743.png" alt class="image--center mx-auto" /></p>
<p>And if you remove the configuration or set <code>layoutName</code> to <code>Default</code>, you should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681722736612/f2fdcd63-d97d-426c-a68b-4056c388dca0.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-head">Head</h2>
<p>In Web applications, it's a good practice to define a page <code>title</code>, and maybe <code>meta tags</code> (like description). Inertia provides a <code>Head</code> component that helps us for this purpose. More info in the <a target="_blank" href="https://inertiajs.com/title-and-meta">official documentation</a>.</p>
<h3 id="heading-our-head-component">Our Head component</h3>
<p>To have a better organization and more flexibility, we will create our <code>Head</code> component that will extend the Inertia's Head component.</p>
<p><strong>/resources/views/Components/Theme/Head.vue</strong></p>
<pre><code class="lang-typescript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> { Head <span class="hljs-keyword">as</span> InertiaHead } <span class="hljs-keyword">from</span> <span class="hljs-string">'@inertiajs/vue3'</span>

defineOptions({
  name: <span class="hljs-string">'ThemeHead'</span>,
})

<span class="hljs-keyword">interface</span> Props {
  item?: <span class="hljs-built_in">any</span>
  title?: <span class="hljs-built_in">string</span>
  description?: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">const</span> props = withDefaults(defineProps&lt;Props&gt;(), {
  item: <span class="hljs-function">() =&gt;</span> ({}),
  title: <span class="hljs-string">''</span>,
  description: <span class="hljs-string">''</span>,
})

<span class="hljs-keyword">const</span> appName = <span class="hljs-string">'My Application'</span>

<span class="hljs-keyword">const</span> title =
  props.item &amp;&amp; props.item.meta_title &amp;&amp; props.item.meta_title != <span class="hljs-string">''</span>
    ? props.item.meta_title
    : props.item &amp;&amp; props.item.title &amp;&amp; props.item.title != <span class="hljs-string">''</span>
    ? props.item.title
    : props.title

<span class="hljs-keyword">const</span> description =
  props.item &amp;&amp; props.item.meta_description &amp;&amp; props.item.meta_description != <span class="hljs-string">''</span>
    ? props.item.meta_description
    : props.item &amp;&amp; props.item.description &amp;&amp; props.item.description != <span class="hljs-string">''</span>
    ? props.item.description
    : props.description
&lt;/script&gt;

&lt;template&gt;
  &lt;InertiaHead :title=<span class="hljs-string">"title ? `${title} | ${appName}` : appName"</span>&gt;
    &lt;meta
      head-key=<span class="hljs-string">"description"</span>
      name=<span class="hljs-string">"description"</span>
      :content=<span class="hljs-string">"description"</span>
    /&gt;
  &lt;/InertiaHead&gt;
&lt;/template&gt;
</code></pre>
<p><strong>What it does</strong></p>
<p>The component defines <code>title</code> and <code>meta-description</code> tags from props</p>
<ul>
<li><p>if an <code>item</code> prop is provided (from PageContent, PageHome, BlogArticle, ...), it looks for:</p>
<ul>
<li><p><code>meta_title</code> and <code>meta_description</code> item properties</p>
</li>
<li><p>then <code>title</code> and <code>description</code> properties if not defined</p>
</li>
</ul>
</li>
<li><p>if not, looks for <code>title</code> and <code>description</code> props</p>
</li>
</ul>
<p>The <code>title</code> is filled out by the <code>appName</code> variable (here it is static text <code>My Application</code>, you can make it dynamic or add your logic according to your project needs).</p>
<h3 id="heading-usage">Usage</h3>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/Head.vue'</span>

...
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">Head</span> <span class="hljs-attr">:item</span>=<span class="hljs-string">"item"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>
  ...
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<p>If we go back to our Twill module, if we define the SEO information:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681727190157/59f0ec14-028e-4602-8d45-37d345534987.png" alt class="image--center mx-auto" /></p>
<p>They will be rendered on the HTML page:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681727258929/9efc5534-a049-40df-8b5a-0604103ab3a0.png" alt /></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Twill, Inertia, Vue and Tailwind improvements]]></title><description><![CDATA[Improve logic, performance, DX of the Laravel Twill Inertia Vue 3 application]]></description><link>https://tech.codivores.com/ltivt-6-twill-inertia-improvements</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-6-twill-inertia-improvements</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Twill]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Fri, 14 Apr 2023 17:02:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681638786326/1113a320-d4cf-4b81-85d0-4899bff7e0f4.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We will use our previous PageContent module to make some improvements.</p>
<h2 id="heading-props-optimization">Props optimization</h2>
<p>When Inertia renders a Page, all the props are JSON encoded in a <code>data-page</code> attribute of the root <code>div</code>.</p>
<p>So, when we add the <code>$item</code> to Inertia in our App Controller,</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Page/Content'</span>, [
    <span class="hljs-string">'item'</span> =&gt; $item,
]);
</code></pre>
<p>all the attributes of the Model are serialized, as you can see in the rendered HTML:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681639480469/9ca99889-2bf2-4c81-85c5-4d61c1a2fd49.png" alt class="image--center mx-auto" /></p>
<p>If you use <strong>Vue.js devtools</strong>, you can inspect the props:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681639593954/cdadfa12-8c77-41bb-b016-67c0885b7a93.png" alt class="image--center mx-auto" /></p>
<p>As you can see, there are a lot of data we don't need, which slows the page load and we don't want to be visible to our visitors.</p>
<p>To improve this, we will use the <code>only()</code> method of the Eloquent Model to return a subset of attributes. You can directly use this in the App Controller:</p>
<p><strong>/app/Http/Controllers/App/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $slug</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        ...

        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Page/Content'</span>, [
            <span class="hljs-string">'item'</span> =&gt; $item-&gt;only([
                <span class="hljs-string">'title'</span>,
                <span class="hljs-string">'meta_title'</span>,
                <span class="hljs-string">'meta_description'</span>,
            ]),
        ]);
    }
}
</code></pre>
<p>We prefer to create a <code>$publicAttributes</code> array attribute in our Model (like existing <code>$translatedAttributes</code>, <code>$slugAttributes</code>, ...) to declare these attributes:</p>
<p><strong>/app/Models/PageContent.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Sortable</span>
</span>{
    ...

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">array</span> $publicAttributes = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
    ];
}
</code></pre>
<p>And use it in the App Controller:</p>
<p><strong>/app/Http/Controllers/App/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $slug</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        ...

        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Page/Content'</span>, [
            <span class="hljs-string">'item'</span> =&gt; $item-&gt;only($item-&gt;publicAttributes),
        ]);
    }
}
</code></pre>
<p>If we inspect the props, we see there are just the needed attributes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681652310124/790943d6-5573-458d-a3bd-62180fa0aee7.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-cache">Cache</h2>
<p>Our content will not change often and loading all the needed data implies multiple queries that necessarily takes some time:</p>
<ul>
<li><p>Search for a published Model with the given slug</p>
</li>
<li><p>Load Model relations: translations, medias, files, blocks</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681653366487/eaebf3e6-adc5-428c-8d70-d72216b49309.png" alt class="image--center mx-auto" /></p>
<p>and we will see in a future article, we will rework some data (mainly for the blocks).</p>
<p>In our projects, we generally try to improve performance by caching database retrieved and reworked data. In the Laravel / Twill context, it can be done like that:</p>
<p><strong>/app/Http/Controllers/App/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">PageContent</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Cache</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $slug</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        $item = Cache::rememberForever(
            <span class="hljs-string">'page.content.'</span> . app()-&gt;getLocale() . <span class="hljs-string">'.'</span> . $slug,
            <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) <span class="hljs-title">use</span> (<span class="hljs-params">$slug</span>) </span>{
                $item = PageContent::publishedInListings()
                    -&gt;forSlug($slug)
                    -&gt;first();

                <span class="hljs-keyword">if</span> ($item !== <span class="hljs-literal">null</span>) {
                    $item-&gt;load(<span class="hljs-string">'translations'</span>, <span class="hljs-string">'medias'</span>, <span class="hljs-string">'blocks'</span>);
                }

                <span class="hljs-keyword">return</span> $item;
            }
        );

        ...
    }
}
</code></pre>
<p>To clear the cache when the content is modified, it is handled in the Repository where Twill provides an <code>afterSave()</code> method we can override:</p>
<p><strong>/app/Repositories/PageContentRepository.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Repositories</span>;

...
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Cache</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ModuleRepository</span>
</span>{
    ...

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">afterSave</span>(<span class="hljs-params">$object, $fields</span>): <span class="hljs-title">void</span>
    </span>{
        <span class="hljs-comment">// Cache clearing.</span>
        <span class="hljs-keyword">foreach</span> (optional($object)-&gt;slugs <span class="hljs-keyword">as</span> $slug) {
            Cache::forget(<span class="hljs-string">'page.content.'</span> . $slug-&gt;locale . <span class="hljs-string">'.'</span> . $slug-&gt;slug);
        }

        <span class="hljs-built_in">parent</span>::afterSave($object, $fields);
    }
}
</code></pre>
<h2 id="heading-vue-props-type-alias">Vue props type alias</h2>
<p>As we use TypeScript, we can benefit from static type checking and many IDE support this language providing auto-complete and warnings. It really improves your DX and we will see how.</p>
<h3 id="heading-defining-types">Defining types</h3>
<p>We create a <code>models.d.ts</code> file in <code>/resources/js/types</code> to define the Eloquent-based objects used in Inertia pages in a <code>Model</code> namespace. For our module, we will create a <code>Page</code> type:</p>
<p><strong>/resources/js/types/models.d.ts</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> Model {
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> Page = {
    title: <span class="hljs-built_in">string</span>
    meta_title?: <span class="hljs-built_in">string</span>
    meta_description?: <span class="hljs-built_in">string</span>
  }
}
</code></pre>
<h3 id="heading-using-types">Using types</h3>
<p>In the previous article, we were using <code>object</code> for our <code>item</code> type, in our IDE (VS Code), that triggers TypeScript warnings:</p>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681663295680/58e12921-91c3-40b4-a05f-7ee4a0a27473.png" alt /></p>
<p>Now we can change the type of our <code>item</code> prop from <code>object</code> to <code>Model.Page</code>:</p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
interface Props {
  <span class="hljs-attr">item</span>: Model.Page
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-gray-200 w-full h-screen flex flex-col justify-center items-center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center text-4xl font-semibold text-gray-900"</span>&gt;</span>
      {{ item.title }}
    <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<p>No more warnings, and we can have information in our IDE about the properties of the object and their types:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681663503601/4f7a0c33-5d89-474e-b25c-64009742c891.png" alt /></p>
<h2 id="heading-vite-typescript-alias">Vite / TypeScript alias</h2>
<p>As our application grows, we will have more and more components, split into different directories to keep a clean architecture (and maybe at some point we will create a new version of the theme, components, ...).</p>
<p>To simplify how we import components into other components and avoid relative paths like <code>../../Theme/Head.vue</code>, we can benefit from <code>alias</code> feature to map an alias to a path and make it available in code and IDE.</p>
<p>We generally define 3 default aliases on a new project:</p>
<ul>
<li><p><code>@Composable</code>: stores our Vue Composition API composables</p>
</li>
<li><p><code>@Form</code>: stores our form components (input, select, switch, ...)</p>
</li>
<li><p><code>@Theme</code>: stores our theme components (head, blocks, ...)</p>
</li>
</ul>
<p>Feel free to create yours according to your project structure.</p>
<h3 id="heading-configuration">Configuration</h3>
<p>The aliases have to be known by Vite (Rollup) and the TypeScript compiler.</p>
<p><strong>/vite.config.js</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    resolve: {
        alias: [
          {
            find: <span class="hljs-string">'@Composable'</span>,
            replacement: <span class="hljs-string">'/resources/js/Composables'</span>
          },
          {
            find: <span class="hljs-string">"@Form"</span>,
            replacement: <span class="hljs-string">`/resources/views/Components/Form`</span>,
          },
          {
            find: <span class="hljs-string">'@Theme'</span>,
            replacement: <span class="hljs-string">'/resources/views/Components/Theme'</span>
          }
        ]
    },

    ...
});
</code></pre>
<p><strong>/tsconfig.json</strong></p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"compilerOptions"</span>: {
    ...

    <span class="hljs-string">"paths"</span>: {
      <span class="hljs-string">"@/*"</span>: [<span class="hljs-string">"resources/*"</span>],
      <span class="hljs-string">"@Composable/*"</span>: [<span class="hljs-string">"resources/js/Composables/*"</span>],
      <span class="hljs-string">"@Form/*"</span>: [<span class="hljs-string">"resources/views/Components/Form/*"</span>],
      <span class="hljs-string">"@Theme/*"</span>: [<span class="hljs-string">"resources/views/Components/Theme/*"</span>]
    },

    ...
  }
}
</code></pre>
<h3 id="heading-usage">Usage</h3>
<p>In your component, you can now import other components more easily.</p>
<p>In the example, the <code>Head</code> component is resolved from <code>@Theme/Head.vue</code> to <code>/resources/views/Components/Theme/Head.vue</code></p>
<pre><code class="lang-typescript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'@Theme/Head.vue'</span>
&lt;/script&gt;

&lt;template&gt;
  &lt;Head&gt;&lt;/Head&gt;
&lt;/template&gt;
</code></pre>
<h2 id="heading-vue-plugins">Vue plugins</h2>
<p>Vue provides many plugins that can improve DX.</p>
<h3 id="heading-autoimport">AutoImport</h3>
<p>When we use functions of libraries in our components, we need to import them in <code>&lt;script setup&gt;</code>. For vue functions for example, it may seem like an unnecessary waste of time:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { computed, ref } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>

<span class="hljs-keyword">const</span> title = ref(<span class="hljs-string">'My Title'</span>)
<span class="hljs-keyword">const</span> meta_title = computed(<span class="hljs-function">() =&gt;</span> <span class="hljs-string">`<span class="hljs-subst">${title.value}</span> | My Application`</span>)
</code></pre>
<p>The AutoImport plugin allows you to skip the first line by automatically generating an auto-imported declaration file 🎉</p>
<pre><code class="lang-typescript"><span class="hljs-comment">/* eslint-disable */</span>
<span class="hljs-comment">/* prettier-ignore */</span>
<span class="hljs-comment">// @ts-nocheck</span>
<span class="hljs-comment">// Generated by unplugin-auto-import</span>
<span class="hljs-keyword">export</span> {}
<span class="hljs-keyword">declare</span> <span class="hljs-built_in">global</span> {
  ...
  <span class="hljs-keyword">const</span> computed: <span class="hljs-keyword">typeof</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'vue'</span>)[<span class="hljs-string">'computed'</span>]
  <span class="hljs-keyword">const</span> ref: <span class="hljs-keyword">typeof</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'vue'</span>)[<span class="hljs-string">'ref'</span>]
  ...
}
<span class="hljs-comment">// for type re-export</span>
<span class="hljs-keyword">declare</span> <span class="hljs-built_in">global</span> {
  <span class="hljs-comment">// @ts-ignore</span>
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> { Component, ComponentPublicInstance, ComputedRef, InjectionKey, PropType, Ref, VNode } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>
}
</code></pre>
<blockquote>
<p>You can use this plugin for many external libraries like <code>vueuse</code>, <code>vue-router</code>, ...</p>
<p>Plugin documentation: <a target="_blank" href="https://github.com/antfu/unplugin-auto-import#configuration">https://github.com/antfu/unplugin-auto-import#configuration</a></p>
</blockquote>
<p><strong>Installation</strong></p>
<pre><code class="lang-bash">yarn add unplugin-auto-import --dev
</code></pre>
<p><strong>Configuration of the plugin in /vite.config.js</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> AutoImport <span class="hljs-keyword">from</span> <span class="hljs-string">'unplugin-auto-import/vite'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    plugins: [
        ...
        AutoImport({
            <span class="hljs-comment">// targets to transform</span>
            include: [
                <span class="hljs-regexp">/\.[tj]sx?$/</span>, <span class="hljs-comment">// .ts, .tsx, .js, .jsx</span>
                /\.vue$/, <span class="hljs-regexp">/\.vue\?vue/</span>, <span class="hljs-comment">// .vue</span>
                /\.md$/, <span class="hljs-comment">// .md</span>
            ],
            imports: [
                <span class="hljs-string">'vue'</span>,
            ],
        }),
    ],
});
</code></pre>
<h3 id="heading-defineoptions">DefineOptions</h3>
<blockquote>
<p>From 3.3 version of Vue, this macro has been integrated into the Vue core package: <a target="_blank" href="https://vuejs.org/api/sfc-script-setup.html#defineoptions">https://vuejs.org/api/sfc-script-setup.html#defineoptions</a></p>
</blockquote>
<p>As we use Vue Composition API, some features are not available in <code>&lt;script setup&gt;</code> like defining component name and other properties, ... and that are available in Vue Options API.</p>
<p>There is a plugin that provides a <code>defineOptions</code> macro that can be used in <code>&lt;script setup&gt;</code></p>
<p><strong>Installation</strong></p>
<pre><code class="lang-bash">yarn add unplugin-vue-define-options --dev
</code></pre>
<p><strong>Configuration of the plugin in /vite.config.js</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> DefineOptions <span class="hljs-keyword">from</span> <span class="hljs-string">'unplugin-vue-define-options/vite'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    plugins: [
        ...
        DefineOptions(),
    ],
});
</code></pre>
<p><strong>Usage</strong></p>
<pre><code class="lang-typescript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
defineOptions({
  name: <span class="hljs-string">'PageContent'</span>,
  layoutName: <span class="hljs-string">'FullPage'</span>,
})
&lt;/script&gt;
</code></pre>
<h2 id="heading-tailwind-automatic-class-sorting-plugin">Tailwind Automatic Class Sorting plugin</h2>
<p>Tailwind provides a Prettier plugin to automatically sort the utility classes according to the <a target="_blank" href="https://tailwindcss.com/blog/automatic-class-sorting-with-prettier#how-classes-are-sorted">official recommended class order</a>, freeing the heads of you and your team from this purpose.</p>
<p><strong>Installation</strong></p>
<pre><code class="lang-bash">yarn add prettier prettier-plugin-tailwindcss --dev
</code></pre>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Enjoy Infomaniak IaaS Public Cloud with Laravel Forge]]></title><description><![CDATA[Provision and deploy your Laravel (or any other PHP / Node / ...) application with Forge on Infomaniak Public Cloud infrastructure]]></description><link>https://tech.codivores.com/infomaniak-public-cloud-with-laravel-forge</link><guid isPermaLink="true">https://tech.codivores.com/infomaniak-public-cloud-with-laravel-forge</guid><category><![CDATA[Laravel]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[hosting]]></category><category><![CDATA[infomaniak]]></category><category><![CDATA[Forge]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Tue, 19 Oct 2021 13:37:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634650489116/T7Rw7avYr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Infomaniak released a new service on September 28, 2021: <strong><a target="_blank" href="https://news.infomaniak.com/en/public-cloud-alternative-gafam">Public Cloud</a></strong>, an IaaS based on Debian and OpenStack . It's the infrastructure they already use for their own services, hosted in Switzerland and committed to a sustainable economy and customer privacy (ISO 14001, ISO 50001, ISO 27001). </p>
<p><strong><a target="_blank" href="https://forge.laravel.com">Laravel Forge</a></strong> is a server management solution for easy provisioning, management and deployment of PHP applications (push to deploy, accessible configuration, database backup, SSL certificates, ...) provided by the Laravel squad.</p>
<p>As Laravel Forge doesn't support Infomaniak as a provider (for now), there are some additional steps to make it work together.</p>
<p>We assume you already have an account on Laravel Forge, Infomaniak and that you <a target="_blank" href="https://www.infomaniak.com/en/support/faq/2603/public-cloud-create-a-new-project">created a project on the Public Cloud service</a>.</p>
<p>Here are the steps to have a running and managed server:</p>
<ul>
<li><a class="post-section-overview" href="#infomaniak-public-cloud">Infomaniak Public Cloud</a><ul>
<li><a class="post-section-overview" href="#create-and-launch-your-instance-in-infomaniak-public-cloud">Create and launch a new Instance</a></li>
<li><a class="post-section-overview" href="#add-ssh-and-web-access-to-your-instance">Add SSH and Web access to your Instance</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#laravel-forge">Laravel Forge</a><ul>
<li><a class="post-section-overview" href="#create-the-server">Create the Server</a></li>
<li><a class="post-section-overview" href="#provision-it">Provision it</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#8jzja">🙌</a></li>
</ul>
<h2 id="heading-infomaniak-public-cloud">Infomaniak Public Cloud</h2>
<h3 id="heading-create-and-launch-your-instance-in-infomaniak-public-cloud">Create and launch your Instance in Infomaniak Public Cloud</h3>
<p>Once you are on your project page, go to <strong>Compute &gt; Instances</strong> menu and click on <strong>Launch Instance</strong> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634546631019/6nMkv3s-K.png" alt="image.png" /></p>
<p>You now have a modal window requiring information you have to fill in multiple steps:</p>
<h4 id="heading-details-basic-information">Details (basic information)</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634546662234/dfATzOIxQ.png" alt="image.png" /></p>
<p>Just give your Instance a name (and a description if you want). You don't need to set an availability zone.</p>
<h4 id="heading-source-os-to-install">Source (OS to install)</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634546711651/4Xi_qmHKB.png" alt="image.png" /></p>
<p>Laravel Forge supports <strong>Ubuntu 20.04 x64</strong> and <strong>Ubuntu 22.04 x64</strong>: add <strong>Ubuntu 22.04 LTS</strong> from the list if your application needs at least PHP 8.1 version, otherwise add <strong>Ubuntu 20.04 x64</strong>.</p>
<h4 id="heading-flavor-ressources-of-the-instance">Flavor (ressources of the Instance)</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634546763417/Tc4V1hpFk.png" alt="image.png" /></p>
<p>Here you have to choose the flavor of your Instance (CPU, RAM, storage).
You can find the pricing for each Instance flavor here:  <a target="_blank" href="https://www.infomaniak.com/en/hosting/public-cloud/prices">https://www.infomaniak.com/en/hosting/public-cloud/prices</a> </p>
<h4 id="heading-networks">Networks</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634546855262/n1cJLHL6m.png" alt="image.png" /></p>
<p>Select the provided Infomaniak IPV4 external network <strong>ext-net1</strong>.</p>
<h4 id="heading-network-ports">Network Ports</h4>
<p>Nothing specific to do here.</p>
<h4 id="heading-security-groups">Security Groups</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634638399592/-i-8DDeU5.png" alt="image.png" /></p>
<p>Here you define the opened ports (entering and exiting) and authorized IP addresses of your Instance, using Security Groups feature.</p>
<p>Keep <strong>default</strong>, for now you will create and add <strong>ssh</strong> (to allow Laravel Forge to manage your Instance), <strong>http</strong> and <strong>https</strong> (to make your Web application reachable) access afterwards.</p>
<h4 id="heading-key-pair">Key Pair</h4>
<p>If you didn't add a SSH key previously, you can import it here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634547055961/9MlzehbT1.png" alt="image.png" /></p>
<p>You can now associate it to your Instance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634547099587/HY7R3TkNB.png" alt="image.png" /></p>
<h4 id="heading-configuration">Configuration</h4>
<p>Nothing specific to do here.</p>
<h4 id="heading-server-groups">Server Groups</h4>
<p>Nothing specific to do here.</p>
<h4 id="heading-scheduler-hints">Scheduler Hints</h4>
<p>Nothing specific to do here.</p>
<h4 id="heading-metadata">Metadata</h4>
<p>Nothing specific to do here.</p>
<h4 id="heading-launch-the-instance">Launch the Instance</h4>
<p>All is now set, you can launch your Instance</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634547213090/BA6Rc175L.png" alt="image.png" /></p>
<p>and see it running a few seconds later.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634547371730/KHYTtuRfW.png" alt="image.png" /></p>
<h3 id="heading-add-ssh-and-web-access-to-your-instance">Add SSH and Web access to your Instance</h3>
<p>On a fresh Infomaniak Public Cloud project, there's no Security Groups created to allow SSH and Web access, you have to create them (you will be able to reuse them on the other Instances you will create in your project afterwards).</p>
<p>To do so, go to <strong>Network &gt; Security Groups</strong> menu and click on <strong>Create Security Group</strong> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634639531441/wYWxa4clt.png" alt="image.png" /></p>
<h4 id="heading-ssh">SSH</h4>
<p>On the opening modal window, give your Security Group a name (and a description if you want) and click on <strong>Create Security Group</strong> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634549039804/qiMZ8GAmY.png" alt="image.png" /></p>
<p>By default, the Security Group gives exiting (Egress) access to any IP on any port. You don't need those rules as they already are set in the <strong>default</strong> Security Group, you can then delete them.</p>
<p>You can now add the Rule you need, so click on <strong>Add Rule</strong> button.</p>
<p>On the opening modal window, you can see a predefined list of protocols, select <strong>SSH</strong>. You can also filter the allowed IP addresses (for Laravel Forge and your own IP addresses for example, you will allow everybody for the moment).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634549079576/GUMtDgq4_.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634549121350/xyiENPmpj.png" alt="image.png" /></p>
<h4 id="heading-web">Web</h4>
<p>Follow the same steps as for SSH for the Security Group creation and default Rules deletion.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634548953991/Fjotr-Jl0.png" alt="image.png" /></p>
<p>Then, for this Security Group, you will add 2 Rules (that are also predefined):</p>
<ul>
<li>HTTP</li>
<li>HTTPS</li>
</ul>
<p>As you want everybody to have access to our Web application, you don't filter IP addresses.</p>
<h4 id="heading-add-the-security-groups-to-your-instance">Add the Security Groups to your Instance</h4>
<p>You can now go back to the <strong>Compute &gt; Instances</strong> menu, and in the <strong>Actions</strong> column of your Instance, click on <strong>Edit Security Groups</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634547983207/M0ycuhMg8K.png" alt="image.png" /></p>
<p>You can now add your <strong>ssh</strong> and <strong>web</strong> Security Groups:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634641007699/BUB2BNTVW.png" alt="image.png" /></p>
<p>Once saved, the rules are instantly applied. All is done now for the Infomaniak Public Cloud part (and it will be quicker for the next Instances, as you'll be able to add the <strong>ssh</strong> and <strong>web</strong> Security Groups directly on Instance creation).</p>
<h2 id="heading-laravel-forge">Laravel Forge</h2>
<h3 id="heading-create-the-server">Create the Server</h3>
<p>On the Server creation section, select <strong>Custom VPS</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643301679924/z1oxciKN5.png" alt="image.png" /></p>
<p>On the form that appears:</p>
<ul>
<li>Select the type of the Server: App Server (including all the softwares needed for a Web application), or you can also split your application in multiple Servers / Instances</li>
<li>Give your Server a name (maybe the same as your Infomaniak Public Cloud Instance is a good idea?)</li>
<li>Set the IP address of the Server (that you can find in the Infomaniak Instances list)</li>
<li>Change the PHP version and Database type if you want</li>
<li>Click on <strong>Create Server</strong> button.</li>
</ul>
<h3 id="heading-provision-it">Provision it</h3>
<p>You will now see a modal window where you can find:</p>
<ul>
<li>The script provided by Laravel Forge to set up your Server and make it fully managed</li>
<li>The passwords for sudo and the Database (if you choose a server type that includes a Database).</li>
</ul>
<blockquote>
<p>Don't click on Close too quickly and keep those information somewhere secure.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643301835894/a9l3oRdz2.png" alt="image.png" /></p>
<p>For a supported Provider, Laravel Forge runs the script automatically without requiring any further action from you. But with Custom Providers, it is to us to run it manually, so:</p>
<ul>
<li>SSH into your Instance (or Server, or whatever you want to call it)<pre><code class="lang-sh">ssh ubuntu@195.15.xxx.xxx
</code></pre>
</li>
<li>Use sudo to be root<pre><code class="lang-sh">sudo -s
root@my-server:/home/ubuntu<span class="hljs-comment">#</span>
</code></pre>
</li>
<li>Run the provisioning command<pre><code class="lang-sh">wget -O forge.sh <span class="hljs-string">"https://forge.laravel.com/servers/XXXXXX/vps?forge_token=xxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXXxxxxxXXxxXXXXxxxxXXXxxxXXXxxxXXXXXX&amp;recipe="</span>; 
bash forge.sh
</code></pre>
</li>
</ul>
<p>If you go back to Laravel Forge and look at your Server, you should now see it being prepared.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643301951903/yMVwyRJoF.png" alt="image.png" /></p>
<h2 id="heading-8jzja">🙌</h2>
<p>Here you are, the Instance is running, installed, configured, managed and the default Laravel Forge site is deployed, you can open a browser and go to your Instance IP address to confirm</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643302586445/oTObg92qT0.png" alt="image.png" /></p>
<p>And of course, you can now deploy your PHP application and enjoy the Infomaniak infrastructure and Laravel Forge quick deploy feature!</p>
]]></content:encoded></item><item><title><![CDATA[My first Twill module]]></title><description><![CDATA[Discover Twill, a CMS package for Laravel, and build with us your first content pages]]></description><link>https://tech.codivores.com/ltivt-5-laravel-twill-first-module</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-5-laravel-twill-first-module</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Twill]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Vue.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Fri, 20 Aug 2021 16:52:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681577663233/d7ce6d6a-8300-4178-939e-2c5b44fc28ba.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 14, 2023</strong></p>
</blockquote>
<p>In this article, we will see the creation and customization of a first content module.</p>
<h2 id="heading-module-creation">Module creation</h2>
<p>In Twill terminology, a Module represents all the files needed to manage a content type: Model (with migration), Repository, Controller, Request and Form view.</p>
<p>A Module can be initiated with the CLI generator, if we look at the <a target="_blank" href="https://twillcms.com/docs/modules/cli-generator.html">official documentation</a>, we see it's an artisan command that takes options:</p>
<pre><code class="lang-bash">php artisan twill:make:module moduleName {options}
</code></pre>
<p>The <code>moduleName</code> is the singular name of your content type and Twill generates some files with plural name (so avoid <code>news</code> as it already ends with a <code>s</code> and will break some functionalities).</p>
<p>The options are (taken from the <a target="_blank" href="https://twill.io/docs/#cli-generator">official documentation</a>):</p>
<blockquote>
<p>--hasBlocks (-B), to use the block editor on your module form</p>
<p>--hasTranslation (-T), to add content in multiple languages</p>
<p>--hasSlug (-S), to generate slugs based on one or multiple fields in your model</p>
<p>--hasMedias (-M), to attach images to your records</p>
<p>--hasFiles (-F), to attach files to your records</p>
<p>--hasPosition (-P), to allow manually reordering of records in the listing screen</p>
<p>--hasRevisions (-R), to allow comparing and restoring past revisions of records</p>
<p>--hasNesting (-N), to enable nested items in the module listing<br />--parentModel=, to generate the route for a nested module</p>
<p>--bladeForm, to generate a Blade form instead of using the new Form builder (more info <a target="_blank" href="https://twillcms.com/blog/twill-3-introducing-oop-builders.html">here</a>)</p>
</blockquote>
<p>Twill is amazing for this as you can choose the features you want to have available for your content, keeping simple content simple. All work with PHP Traits and additional classes, so if you forget an option, you can add it later based on sample codes.</p>
<h3 id="heading-lets-create-our-first-module-to-handle-static-pages">Let's create our first Module to handle static pages</h3>
<p>We will call this Module <em>contentPage</em> and we will need Blocks (to have flexible content), Translations, Slugs, Medias, Position (to order them in the administration) and Revisions (we will not attach Files directly but maybe through Blocks):</p>
<pre><code class="lang-bash">php artisan twill:make:module pageContent -BTSMPR 

<span class="hljs-comment"># If you want to handle the form through a Blade template, you can add the --bladeForm option (you still can create the file manually afterward</span>
php artisan twill:make:module pageContent -BTSMPR --bladeForm
</code></pre>
<p>The output we can see in our terminal:</p>
<pre><code class="lang-php">Migration created successfully! Add some fields!
Models created successfully! Fill your fillables!
Repository created successfully! Control all the things!
Controller created successfully! Define your index/browser/form endpoints options!
Form request created successfully! Add some validation rules!
Form view created successfully! You can now <span class="hljs-keyword">include</span> your form fields.

 <span class="hljs-keyword">Do</span> you also want to generate the preview file? [no]:
  [<span class="hljs-number">0</span>] no
  [<span class="hljs-number">1</span>] yes
 &gt; 

The following snippet has been added to routes/twill.php:
-----
TwillRoutes::module(<span class="hljs-string">'pageContents'</span>);
-----
To add a navigation entry add the following to your AppServiceProvider BOOT method.
-----
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillNavigation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Navigation</span>\<span class="hljs-title">NavigationLink</span>;
TwillNavigation::addLink(
    NavigationLink::make()-&gt;forModule(<span class="hljs-string">'pageContents'</span>)
);
-----
<span class="hljs-keyword">Do</span> not forget to migrate your database after modifying the migrations.

Enjoy.
</code></pre>
<h3 id="heading-files-generated">Files generated</h3>
<p>It generates the following files in your application:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681566941833/8602ad02-6aa6-4308-a5f6-cf0d0e22de9b.png" alt /></p>
<p>If you added the <code>--bladeForm</code> option, you also have the form template file:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681566962922/23e66d76-9ad3-44e9-876c-c919497db3a9.png" alt /></p>
<h3 id="heading-what-next">What next</h3>
<ul>
<li><p>Check or edit the Routes according to the structure your want</p>
</li>
<li><p>Add a navigation entry</p>
</li>
<li><p>Customize the fields of the Model</p>
</li>
<li><p>Create the form accordingly (Blade components or OOP builder)</p>
</li>
<li><p>Customize the admin Controller if needed</p>
</li>
<li><p>Morph map</p>
</li>
</ul>
<h2 id="heading-routes-and-navigation-configuration">Routes and Navigation configuration</h2>
<h3 id="heading-routes-configuration">Routes configuration</h3>
<p>Since Twill 3, the module routes are automatically added at the end of the file as a root entry (if you are still using Twill 2, you need to add it manually).</p>
<p><strong>/routes/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillRoutes</span>;

TwillRoutes::module(<span class="hljs-string">'pageContents'</span>);
</code></pre>
<h3 id="heading-navigation-entry">Navigation entry</h3>
<p>Since Twill 3, there is a new way to manage navigation, registering it in the AppServiceProvider (you still can use the legacy method defining your navigation in a <code>config/twill-navigation.php</code> file). More info in the <a target="_blank" href="https://twillcms.com/docs/getting-started/navigation.html">official documentation</a></p>
<p>You can copy/paste what the CLI output suggested:</p>
<p><strong>/app/Providers/AppServiceProvider.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Providers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillNavigation</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">View</span>\<span class="hljs-title">Components</span>\<span class="hljs-title">Navigation</span>\<span class="hljs-title">NavigationLink</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppServiceProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ServiceProvider</span>
</span>{
    <span class="hljs-comment">/**
     * Bootstrap any application services.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        TwillNavigation::addLink(
            NavigationLink::make()-&gt;forModule(<span class="hljs-string">'pageContents'</span>)
        );
    }
}
</code></pre>
<p>If you want to customize the title in the navigation, you can chain it with the call of <code>title()</code> method (don’t forget to add <code>use Illuminate\Support\Str;</code> if you use the example below):</p>
<pre><code class="lang-php">    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        TwillNavigation::addLink(
            NavigationLink::make()
                -&gt;title(Str::ucfirst(__(<span class="hljs-string">'pages'</span>)))
                -&gt;forModule(<span class="hljs-string">'pageContents'</span>)
        );
    }
</code></pre>
<p>To see our Module administration interface without triggering an error, we need to execute the migration via <code>php artisan migrate</code>. We will do it later as we want to customize the attributes of our model, but here is an example of what you will see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681568293228/dcfda5dc-33dd-4767-9f11-e869aed065f5.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-navigation-reorganization">Navigation reorganization</h3>
<p>The default configuration adds our Module to the primary level of the navigation. As we want to organize our navigation, we will modify this configuration to access our Module at a secondary level of a global <code>Content</code> entry (Twill allows you to have up to 3 levels for your navigation):</p>
<p><strong>/routes/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">TwillRoutes</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;

Route::group([<span class="hljs-string">'prefix'</span> =&gt; <span class="hljs-string">'content'</span>], <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    TwillRoutes::module(<span class="hljs-string">'pageContents'</span>);
});
</code></pre>
<p><strong>/app/Providers/AppServiceProvider.php</strong></p>
<pre><code class="lang-php">    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        TwillNavigation::addLink(
            NavigationLink::make()
                -&gt;title(Str::ucfirst(__(<span class="hljs-string">'content'</span>)))
                -&gt;forModule(<span class="hljs-string">'pageContents'</span>)
                -&gt;doNotAddSelfAsFirstChild()
                -&gt;setChildren([
                    NavigationLink::make()
                        -&gt;title(Str::ucfirst(__(<span class="hljs-string">'pages'</span>)))
                        -&gt;forModule(<span class="hljs-string">'pageContents'</span>)
                ]),
        );
    }
</code></pre>
<p><strong>What it does</strong></p>
<p>For the route, using standard Laravel routing, we encapsulate our Module routes definition in a group with the <code>content</code> prefix. As Twill routes already add <code>twill</code> prefix, our Module routes names will start with <code>twill.content.pageContents</code></p>
<p>For the Twill navigation, we encapsulate our module as a child of a primary <code>content</code> navigation link which has the following attributes:</p>
<ul>
<li><p>title(): the text displayed in the navigation</p>
</li>
<li><p>forModule(): the module that will be displayed on click, for now, we want the index of our Module</p>
</li>
<li><p>doNotAddSelfAsFirstChild(): without this method, we would have 2 entries on the secondary level: <code>Content</code> and <code>Pages</code></p>
</li>
<li><p>setChildren(): the list of the navigation links for the secondary level</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681569399937/97f97a47-855b-4a9c-b28e-d9cf9a1f47df.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-model-customization">Model customization</h2>
<p>The migration, model and form files created by the generator are a template with default fields.</p>
<p>In our case, we want:</p>
<ul>
<li><p>a title that can be translated</p>
</li>
<li><p>meta title and description that can be translated</p>
</li>
<li><p>a position to sort manually our pages in the listing of the administration interface</p>
</li>
<li><p>a block editor for all the content (we will focus on this part in a later article)</p>
</li>
</ul>
<p>Here is what the final files look like.</p>
<p><strong>/database/migrations/..._create_page_contents_tables.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Migrations</span>\<span class="hljs-title">Migration</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Schema</span>\<span class="hljs-title">Blueprint</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Schema</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreatePageContentsTables</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::create(<span class="hljs-string">'page_contents'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultTableFields($table);
        });

        Schema::table(<span class="hljs-string">'page_contents'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;after(<span class="hljs-string">'id'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$table</span>) </span>{
                $table-&gt;integer(<span class="hljs-string">'position'</span>)-&gt;unsigned()-&gt;nullable();
            });
        });

        Schema::create(<span class="hljs-string">'page_content_translations'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultTranslationsTableFields($table, <span class="hljs-string">'page_content'</span>);
        });

        Schema::table(<span class="hljs-string">'page_content_translations'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;after(<span class="hljs-string">'page_content_id'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$table</span>) </span>{
                $table-&gt;string(<span class="hljs-string">'title'</span>, <span class="hljs-number">200</span>)-&gt;nullable();
                $table-&gt;string(<span class="hljs-string">'meta_title'</span>, <span class="hljs-number">100</span>)-&gt;nullable();
                $table-&gt;text(<span class="hljs-string">'meta_description'</span>, <span class="hljs-number">200</span>)-&gt;nullable();
            });
        });

        Schema::create(<span class="hljs-string">'page_content_slugs'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultSlugsTableFields($table, <span class="hljs-string">'page_content'</span>);
        });

        Schema::create(<span class="hljs-string">'page_content_revisions'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            createDefaultRevisionsTableFields($table, <span class="hljs-string">'page_content'</span>);
        });
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span>(<span class="hljs-params"></span>)
    </span>{
        Schema::dropIfExists(<span class="hljs-string">'page_content_revisions'</span>);
        Schema::dropIfExists(<span class="hljs-string">'page_content_translations'</span>);
        Schema::dropIfExists(<span class="hljs-string">'page_content_slugs'</span>);
        Schema::dropIfExists(<span class="hljs-string">'page_contents'</span>);
    }
}
</code></pre>
<blockquote>
<p>As the <code>createDefault...()</code> functions create the timestamp and soft delete columns, we use an update of the structure to add our columns in a more pleasant order but it's not a requirement, you can define your columns in the <code>Schema::create()</code> closure</p>
</blockquote>
<p>We can now run our migration to create the tables for our Module:</p>
<pre><code class="lang-bash">php artisan migrate
</code></pre>
<p><strong>/app/Models/PageContent.php</strong></p>
<pre><code class="lang-php"><span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">protected</span> $fillable = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
        <span class="hljs-string">'published'</span>,
        <span class="hljs-string">'position'</span>,
    ];

    <span class="hljs-keyword">public</span> $translatedAttributes = [
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'meta_title'</span>,
        <span class="hljs-string">'meta_description'</span>,
        <span class="hljs-string">'active'</span>,
    ];
<span class="hljs-comment">// ...</span>
</code></pre>
<blockquote>
<p>Twill uses Laravel Eloquent mass assignment, so we need to declare all our attributes in the <code>fillable</code> property, and the translatable attributes in the <code>translatedAttributes</code> property (it's a common mistake to forget to add our attributes or a new one created after as Twill won't trigger an error when you edit your content, but your value will not be saved)</p>
</blockquote>
<h2 id="heading-form-creation">Form creation</h2>
<p>In Twill 2, forms were Blade components, Twill 3 introduces a Form builder allowing you to define the form in PHP in the module controller.</p>
<p>Blade components give you more flexibility for very complex forms or if you want to integrate custom HTML. For standard forms, the Form builder seems to do the job. We will see both ways.</p>
<h3 id="heading-form-through-blade-components">Form through Blade components</h3>
<p>If you set the <code>--bladeForm</code> option on the module creation, the file already exists, if not you have to create it manually.</p>
<p><strong>/resources/views/twill/pageContents/form.blade.php</strong></p>
<pre><code class="lang-scss"><span class="hljs-keyword">@extends</span>(<span class="hljs-string">'twill::layouts.form'</span>)

<span class="hljs-keyword">@section</span>(<span class="hljs-string">'contentFields'</span>)

    &lt;x-twill::block-editor
        :withoutSeparator=<span class="hljs-string">"true"</span>
    /&gt;

<span class="hljs-keyword">@stop</span>

<span class="hljs-keyword">@section</span>(<span class="hljs-string">'sideFieldsets'</span>)
    <span class="hljs-keyword">@formFieldset</span>([ <span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'seo'</span>, <span class="hljs-string">'title'</span> =&gt; <span class="hljs-string">'Référencement'</span>])

        &lt;x-twill::input
            label=<span class="hljs-string">"Title"</span>
            name=<span class="hljs-string">"meta_title"</span>
            :translated=<span class="hljs-string">"true"</span>
            :maxlength=<span class="hljs-string">"100"</span>
        /&gt;

        &lt;x-twill::input
            label=<span class="hljs-string">"Description"</span>
            name=<span class="hljs-string">"meta_description"</span>
            :translated=<span class="hljs-string">"true"</span>
            :maxlength=<span class="hljs-string">"200"</span>
        /&gt;

    <span class="hljs-keyword">@endformFieldset</span>
<span class="hljs-keyword">@stop</span>
</code></pre>
<blockquote>
<p>In the <code>contentFields</code> section, we remove the title and add a <code>block_editor</code> field (the <code>withoutSeparator</code> option just removes a separator displayed before it on the edit page)</p>
<p>We create a <code>sideFieldsets</code> section where we add our SEO fields</p>
</blockquote>
<h3 id="heading-form-through-form-builder">Form through Form builder</h3>
<p>The configuration is made directly in the module controller.</p>
<p><strong>/app/Http/Controllers/Twill/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">ModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseModuleController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">TwillModelContract</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">BlockEditor</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fields</span>\<span class="hljs-title">Input</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Fieldset</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">Forms</span>\<span class="hljs-title">Form</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getForm</span>(<span class="hljs-params">TwillModelContract $model</span>): <span class="hljs-title">Form</span>
    </span>{
        $form = <span class="hljs-built_in">parent</span>::getForm($model);

        $form-&gt;add(
            BlockEditor::make()
                -&gt;withoutSeparator()
        );

        <span class="hljs-keyword">return</span> $form;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSideFieldsets</span>(<span class="hljs-params">TwillModelContract $model</span>): <span class="hljs-title">Form</span>
    </span>{
        $form = <span class="hljs-built_in">parent</span>::getSideFieldsets($model);

        $form-&gt;addFieldset(
            Fieldset::make()
                -&gt;title(<span class="hljs-string">'SEO'</span>)
                -&gt;id(<span class="hljs-string">'seo'</span>)
                -&gt;fields([
                    Input::make()
                        -&gt;name(<span class="hljs-string">'meta_title'</span>)
                        -&gt;label(<span class="hljs-string">'Title'</span>)
                        -&gt;translatable()
                        -&gt;maxLength(<span class="hljs-number">100</span>),

                    Input::make()
                        -&gt;name(<span class="hljs-string">'meta_description'</span>)
                        -&gt;label(<span class="hljs-string">'Description'</span>)
                        -&gt;translatable()
                        -&gt;maxLength(<span class="hljs-number">200</span>),
                ])
        );

        <span class="hljs-keyword">return</span> $form;
    }
}
</code></pre>
<blockquote>
<p>The <code>getForm()</code> method defines the fields or fieldsets in the left column</p>
<p>The <code>getSideFieldsets()</code> method defines the additional fields or fieldsets in the side/right column</p>
</blockquote>
<h3 id="heading-form-in-action">Form in action</h3>
<p>Now we can manage our content in the administration interface. Let's click on the <em>Add new</em> button to see a modal asking us for the title of our page (the permalink aka slug is automatically generated but you can edit it). You can fill in the information for each language and also change the publication status of your content globally and for each language):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681569793440/ec3f55d8-ee83-4be3-8372-a980e6219252.png" alt class="image--center mx-auto" /></p>
<p>And here is the form for editing our content:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681570266696/8d092b35-1649-4982-8e90-3e855fa7526d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-controller-customization">Controller customization</h2>
<p>Maybe have you seen on the form screenshot an URL under the title. Twill displays a link to our front-end content based on the domain name, the module name and then the slug of our page. This behavior, and many more things (like the columns displayed in the listing, the default order, ...) can be customized in the admin Controller.</p>
<p>Here is some basic customization:</p>
<p><strong>/app/Http/Controllers/Admin/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Twill</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">A17</span>\<span class="hljs-title">Twill</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">Admin</span>\<span class="hljs-title">ModuleController</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseModuleController</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseModuleController</span>
</span>{
    <span class="hljs-keyword">protected</span> $moduleName = <span class="hljs-string">'pageContents'</span>;

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setUpController</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;setPermalinkBase(<span class="hljs-string">''</span>);
        <span class="hljs-keyword">$this</span>-&gt;enableReorder();
    }
}
</code></pre>
<blockquote>
<p>We set an empty <code>permalinkBase</code> property to tell Twill our pages will be available directly under the Web root path.</p>
<p>We enable reordering</p>
</blockquote>
<p>More info in the <a target="_blank" href="https://twillcms.com/docs/modules/controllers.html#content-controller-setup">official documentation</a></p>
<h2 id="heading-morph-map">Morph map</h2>
<p>Twill uses many pivot tables to handle polymorphic relationships with the module Models: medias, files, blocks, features, tags and <a target="_blank" href="https://spatie.be/docs/laravel-activitylog/v4/introduction">Spatie activity log package</a>.<br />The default behavior is to store the fully qualified class name in the database, with MorphMap you can provide an alias that improves readability and decouples the class name from the stored data.</p>
<p>Since Laravel 8.59, you can enforce a morph map for every class used in a morph, preventing you from forgetting to define the morph map when you create a new Twill module.</p>
<p><strong>/app/Providers/AppServiceProvider.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Providers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Relations</span>\<span class="hljs-title">Relation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppServiceProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ServiceProvider</span>
</span>{
    <span class="hljs-comment">/**
     * Bootstrap any application services.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        Relation::enforceMorphMap([
            <span class="hljs-string">'pageContent'</span> =&gt; <span class="hljs-string">'App\Models\PageContent'</span>,
        ]);
    }
}
</code></pre>
<h2 id="heading-lets-talk-about-front-end-and-inertia">Let's talk about Front-end and Inertia</h2>
<p>This module aims to display content pages on our front-end. To do so, we need:</p>
<ul>
<li><p>a Laravel Route</p>
</li>
<li><p>a Laravel Controller</p>
</li>
<li><p>an Inertia Page</p>
</li>
</ul>
<h3 id="heading-route">Route</h3>
<p>Our route catches all GET HTTP requests with a slug from the Web root path:</p>
<p><strong>/routes/web.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>\<span class="hljs-title">PageContentController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;

Route::get(<span class="hljs-string">'/{slug}'</span>, [PageContentController::class, <span class="hljs-string">'show'</span>])-&gt;name(<span class="hljs-string">'page.content.show'</span>);
</code></pre>
<h3 id="heading-controller">Controller</h3>
<p>To handle the logic, we need a Controller. As Twill already stores its controllers in a <code>Twill</code> directory of <code>/app/Http/Controllers</code>, we will store our application controllers in a <code>App</code> directory (it is not mandatory, but it may help in your project organization, and of course, you can choose the name you want, like <code>Site</code>, <code>Front</code>, ...).</p>
<p>The first step is to move the default <code>/app/Http/Controllers/Controller.php</code> in <code>app/Http/Controllers/App/</code> and change its namespace (again, it is not mandatory):</p>
<p><strong>/app/Http/Controllers/App/Controller.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">Access</span>\<span class="hljs-title">AuthorizesRequests</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Validation</span>\<span class="hljs-title">ValidatesRequests</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Routing</span>\<span class="hljs-title">Controller</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseController</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Controller</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseController</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">AuthorizesRequests</span>, <span class="hljs-title">ValidatesRequests</span>;
}
</code></pre>
<p>Now we can create our App Module controller:</p>
<p><strong>/app/Http/Controllers/App/PageContentController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">App</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">PageContent</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PageContentController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">show</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $slug</span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        $item = PageContent::publishedInListings()
            -&gt;forSlug($slug)
            -&gt;first();

        abort_if($item === <span class="hljs-literal">null</span>, Response::HTTP_NOT_FOUND);

        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Page/Content'</span>, [
            <span class="hljs-string">'item'</span> =&gt; $item,
        ]);
    }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Load the Twill Model (item), from its query builder:</p>
<ul>
<li><p>publishedInListings(): scope that adds <code>published == true</code> and if you use publish dates (publish_start_date and publish_end_date), checks that the Model is currently visible (<code>publish_start_date &lt;= now()</code> and <code>publish_end_date &gt;= now()</code>)</p>
</li>
<li><p>forSlug(string $slug): scope that looks for Models that have an <strong>active slug</strong> that matches the string given <strong>for the current locale</strong></p>
</li>
<li><p>first(): return the first Model that matches the query criterias and return <code>null</code> if none are found</p>
</li>
</ul>
</li>
<li><p>Return a 404 if the Model is <code>null</code></p>
</li>
<li><p>Renders the Inertia <code>Page/Content</code> Page with <code>item</code> as a prop</p>
</li>
</ul>
<h3 id="heading-page">Page</h3>
<p>The last step, we create our Inertia Page as a Vue Single-File Component (SFC).</p>
<p><strong>/resources/views/Pages/Page/Content.vue</strong></p>
<pre><code class="lang-javascript">&lt;script setup lang=<span class="hljs-string">"ts"</span>&gt;
interface Props {
  <span class="hljs-attr">item</span>: object
}

defineProps&lt;Props&gt;()
&lt;/script&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-gray-200 w-full h-screen flex flex-col justify-center items-center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center text-4xl font-semibold text-gray-900"</span>&gt;</span>
      {{ item.title }}
    <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span>
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Declare the <code>item</code> prop as a generic object (we will see later how to improve the props declarations)</p>
</li>
<li><p>Display the <code>item.title</code> in a centered full-screen page</p>
</li>
</ul>
<h3 id="heading-final-result">Final result</h3>
<p>If you publish your page (status Live), you can click on the permalink to open the front-end page in a new tab:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681638122771/c451b8a6-a9d4-4ce9-a324-aa5ce22d15bd.png" alt class="image--center mx-auto" /></p>
<p>and you should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681638296220/adaa486f-951d-4ec5-89b9-552cbc3554a4.png" alt class="image--center mx-auto" /></p>
<hr />
<p><strong>We now have a first module to handle content pages, we will see in later articles how to improve logic, performance and handle more complex content structure with blocks</strong></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[What about building a CMS, let's Twill]]></title><description><![CDATA[Discover Twill, a CMS package for Laravel, get the basic configuration tips]]></description><link>https://tech.codivores.com/ltivt-4-laravel-twill-basics</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-4-laravel-twill-basics</guid><category><![CDATA[Laravel]]></category><category><![CDATA[cms]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Twill]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 19 Aug 2021 18:27:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1629392987770/Vblh721Vm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 14, 2023</strong></p>
</blockquote>
<h2 id="heading-dependencies-installation">Dependencies installation</h2>
<p>Twill comes as a Laravel package that can be installed via Composer. You can refer to the <a target="_blank" href="https://twillcms.com/docs/">official documentation</a> for more information.</p>
<pre><code class="lang-bash">composer require area17/twill:<span class="hljs-string">"^3.0"</span>
</code></pre>
<h2 id="heading-twill-installation">Twill installation</h2>
<h4 id="heading-what-does-that-mean">What does that mean?</h4>
<p>Twill installation will</p>
<ul>
<li><p>Create configuration files</p>
<ul>
<li><p><code>twill.php</code>: global configuration of the package</p>
</li>
<li><p><code>translatable.php</code>: Twill uses <a target="_blank" href="https://github.com/Astrotomic/laravel-translatable">astrotomic/laravel-translatable</a> package to handle multi-language content</p>
</li>
</ul>
</li>
<li><p>Create a <code>twill.php</code> route file to declare the routes of our modules</p>
</li>
<li><p>Publish the assets of the administration interface (Twill is built with Vue.js 2)</p>
</li>
<li><p>Migrate all the package tables: twill users, settings, blocks, medias, files, ...</p>
</li>
<li><p>Prompt for a superadmin account creation (you can create it or new ones later with this command <code>php artisan twill:superadmin</code>)</p>
</li>
</ul>
<p>If you want to change the default table names, create the <code>twill.php</code> config file before proceeding to the installation and define your custom names.</p>
<p><strong>Default table names</strong></p>
<pre><code class="lang-php">    <span class="hljs-string">'blocks_table'</span> =&gt; <span class="hljs-string">'twill_blocks'</span>,
    <span class="hljs-string">'features_table'</span> =&gt; <span class="hljs-string">'twill_features'</span>,
    <span class="hljs-string">'fileables_table'</span> =&gt; <span class="hljs-string">'twill_fileables'</span>,
    <span class="hljs-string">'files_table'</span> =&gt; <span class="hljs-string">'twill_files'</span>,
    <span class="hljs-string">'mediables_table'</span> =&gt; <span class="hljs-string">'twill_mediables'</span>,
    <span class="hljs-string">'medias_table'</span> =&gt; <span class="hljs-string">'twill_medias'</span>,
    <span class="hljs-string">'password_resets_table'</span> =&gt; <span class="hljs-string">'twill_password_resets'</span>,
    <span class="hljs-string">'related_table'</span> =&gt; <span class="hljs-string">'twill_related'</span>,
    <span class="hljs-string">'settings_table'</span> =&gt; <span class="hljs-string">'twill_settings'</span>,
    <span class="hljs-string">'tagged_table'</span> =&gt; <span class="hljs-string">'twill_tagged'</span>,
    <span class="hljs-string">'tags_table'</span> =&gt; <span class="hljs-string">'twill_tags'</span>,
    <span class="hljs-string">'users_oauth_table'</span> =&gt; <span class="hljs-string">'twill_users_oauth'</span>,
    <span class="hljs-string">'users_table'</span> =&gt; <span class="hljs-string">'twill_users'</span>,
</code></pre>
<p>We generally change the table names to set <code>admin</code> prefix instead of <code>twill</code> for admin users and add <code>content</code> prefix for all other tables.</p>
<p><strong>/config/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">return</span> [

    <span class="hljs-comment">/*
    |--------------------------------------------------------------------------
    | Twill default tables naming configuration
    |--------------------------------------------------------------------------
    |
    */</span>

    <span class="hljs-string">'blocks_table'</span> =&gt; <span class="hljs-string">'content_blocks'</span>,
    <span class="hljs-string">'features_table'</span> =&gt; <span class="hljs-string">'content_features'</span>,
    <span class="hljs-string">'fileables_table'</span> =&gt; <span class="hljs-string">'content_fileables'</span>,
    <span class="hljs-string">'files_table'</span> =&gt; <span class="hljs-string">'content_files'</span>,
    <span class="hljs-string">'mediables_table'</span> =&gt; <span class="hljs-string">'content_mediables'</span>,
    <span class="hljs-string">'medias_table'</span> =&gt; <span class="hljs-string">'content_medias'</span>,
    <span class="hljs-string">'password_resets_table'</span> =&gt; <span class="hljs-string">'admin_password_resets'</span>,
    <span class="hljs-string">'related_table'</span> =&gt; <span class="hljs-string">'content_related'</span>,
    <span class="hljs-string">'settings_table'</span> =&gt; <span class="hljs-string">'content_settings'</span>,
    <span class="hljs-string">'tagged_table'</span> =&gt; <span class="hljs-string">'content_tagged'</span>,
    <span class="hljs-string">'tags_table'</span> =&gt; <span class="hljs-string">'content_tags'</span>,
    <span class="hljs-string">'users_oauth_table'</span> =&gt; <span class="hljs-string">'admin_users_oauth'</span>,
    <span class="hljs-string">'users_table'</span> =&gt; <span class="hljs-string">'admin_users'</span>,

];
</code></pre>
<h4 id="heading-ok-lets-do-it">Ok, let's do it</h4>
<p>We have an email address <em>(no mail will be sent)</em> and a password, we are ready for the installation process, so let's execute the following command:</p>
<pre><code class="lang-bash">php artisan twill:install
</code></pre>
<h2 id="heading-where-is-my-twill">Where is my Twill</h2>
<p>The administration interface is available by default as <code>admin</code> path of your <code>APP_URL</code> environment variable (defined when you installed Laravel in your <code>/.env</code> file): <code>http://localhost/admin</code>.</p>
<p>Twill allows you to have it available where you want with environment variables:</p>
<ul>
<li><p>For a fully dedicated domain: set an <code>ADMIN_APP_URL</code> environment variable with the URL (ex: <code>ADMIN_APP_URL=tech.codivores.com</code>)</p>
</li>
<li><p>As a path of your main domain: set an <code>ADMIN_APP_PATH</code> environment variable with the name of the subdirectory (ex: <code>ADMIN_APP_PATH=/administration</code>).</p>
</li>
</ul>
<p>You can find more configuration options in the <a target="_blank" href="https://twillcms.com/docs/getting-started/installation.html#content-admin-path-and-domain">official documentation</a> like strict domain handling when using a path.</p>
<p>In most cases, we make the administration available as a path of the main domain. And depending on our clients, we set the <code>ADMIN_APP_PATH</code> environment variable in the <code>.env</code> file (or as an OS environment variable) with the name they want and that is not too obvious for an administration interface.</p>
<p>/!\ If you are using a path, there's a little buggy behavior: if you try to login through <code>http://localhost/admin/login.php</code> instead of <code>http://localhost/admin</code>, you are well logged in but redirected to the <code>APP_URL</code>... To prevent this, you can edit the default <code>auth_login_redirect_path</code> config:</p>
<p><strong>/config/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> [

    <span class="hljs-comment">/*
    |--------------------------------------------------------------------------
    | Twill Auth related configuration
    |--------------------------------------------------------------------------
    |
     */</span>
    <span class="hljs-string">'auth_login_redirect_path'</span> =&gt; env(<span class="hljs-string">'ADMIN_APP_PATH'</span>, <span class="hljs-string">'/admin'</span>),

];
</code></pre>
<p>We can now go to <code>http://localhost/admin</code> in a browser and see the login page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681485807160/f3df7f2b-397c-419f-87ca-ecd7b14e1e40.png" alt class="image--center mx-auto" /></p>
<p>Filling the login form with the superadmin email and password we set earlier, we can see a beautiful empty administration interface 🙌.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681485842850/7401a84c-f3bf-4345-9e7f-e7ed9a7b04c4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-multi-language-configuration">Multi-language configuration</h2>
<p>Twill allows you to manage your content in multiple languages and also have the administration in different languages.</p>
<h4 id="heading-multi-language-in-the-front">Multi-language in the Front</h4>
<p>Just add your locales in the <code>locales</code> array of the <a target="_blank" href="https://github.com/Astrotomic/laravel-translatable">astrotomic/laravel-translatable</a> package configuration file. We will just add French beside the default English locale for the tutorial.</p>
<p><strong>/config/translatable.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">return</span> [

    <span class="hljs-comment">/*
    |--------------------------------------------------------------------------
    | Application Locales
    |--------------------------------------------------------------------------
    |
    | Contains an array with the applications available locales.
    |
    */</span>

    <span class="hljs-string">'locales'</span> =&gt; [
        <span class="hljs-string">'en'</span>,
        <span class="hljs-string">'fr'</span>,
    ],
</code></pre>
<h4 id="heading-multi-language-in-the-back">Multi-language in the Back</h4>
<p>Twill handles some locales for the administration interface (at this time: <code>ar, bs, de, en, fr, nl, pl, pt, ru, tr, zh-Hans</code> - feel free to contribute and add yours).</p>
<p>Admin users can choose their language on their profile page, but you can change the default <code>en</code> locale in the Twill configuration file if you prefer.</p>
<p><strong>/config/twill.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">return</span> [

    <span class="hljs-comment">/*
    |--------------------------------------------------------------------------
    | Twill app locale
    |--------------------------------------------------------------------------
    |
    */</span>

    <span class="hljs-string">'locale'</span> =&gt; <span class="hljs-string">'fr'</span>,
</code></pre>
<h2 id="heading-ready-to-create-content">Ready to create content?</h2>
<p>Go to the next article to create a first module.</p>
<hr />
<p><strong>We now have a basic (for now) but working administration interface to manage content, we will see in later articles how to create content and display it on our front-end with Inertia and handle more complex content structure</strong></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Give some style with Tailwind]]></title><description><![CDATA[Install and configure Tailwind with Vite, make some fun with Inertia on our Laravel application]]></description><link>https://tech.codivores.com/ltivt-3-tailwind</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-3-tailwind</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Inertia.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 15 Jul 2021 20:50:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627665023530/e2KqWfCvm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 14, 2023</strong></p>
</blockquote>
<h2 id="heading-installation-and-configuration">Installation and configuration</h2>
<p>For these steps, we will mainly follow the <a target="_blank" href="https://tailwindcss.com/docs/installation/using-postcss">official documentation</a>.</p>
<h3 id="heading-dependencies-installation">Dependencies installation</h3>
<pre><code class="lang-bash"><span class="hljs-comment"># Tailwind and its dependencies: PostCSS, Autoprefixer</span>
yarn add tailwindcss postcss autoprefixer --dev
</code></pre>
<h3 id="heading-configuration-files-generation">Configuration files generation</h3>
<p>Let's generate <code>tailwind.config.js</code> and <code>postcss.config.js</code> files in our project root folder with the default configuration. That can be done manually or with the following command:</p>
<pre><code class="lang-bash">npx tailwindcss init -p
</code></pre>
<h3 id="heading-postcss-configuration">PostCSS configuration</h3>
<p>Here we keep the default configuration.</p>
<p><strong>/postcss.config.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: {
    <span class="hljs-attr">tailwindcss</span>: {},
    <span class="hljs-attr">autoprefixer</span>: {},
  },
}
</code></pre>
<h3 id="heading-tailwind-configuration">Tailwind Configuration</h3>
<p>From the default configuration, we add the paths (relative to the project root) to all of our files that can contain Tailwind class names (Blade templates, Vue components, ...)</p>
<p><strong>/tailwind.config.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import('tailwindcss').Config}</span> </span>*/</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">content</span>: [
    <span class="hljs-string">'./resources/**/*.blade.php'</span>,
    <span class="hljs-string">'./resources/**/*.vue'</span>,
  ],
  <span class="hljs-attr">theme</span>: {
    <span class="hljs-attr">extend</span>: {},
  },
  <span class="hljs-attr">plugins</span>: [],
}
</code></pre>
<h2 id="heading-integration-in-our-application">Integration in our application</h2>
<ul>
<li><p>Create a CSS file with Tailwind directives</p>
</li>
<li><p>Import it into our application</p>
</li>
<li><p>Use it in our root view</p>
</li>
</ul>
<p>We can use the default <code>/resources/css/app.css</code> that comes with Laravel (or feel free to do as you want) and we add the standard Tailwind directives.</p>
<p><strong>/resources/css/app.css</strong></p>
<pre><code class="lang-css"><span class="hljs-keyword">@tailwind</span> base;
<span class="hljs-keyword">@tailwind</span> components;
<span class="hljs-keyword">@tailwind</span> utilities;
</code></pre>
<p>Then we import it into our TypeScript application file.</p>
<p><strong>/resources/js/app.ts</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createApp, h, type DefineComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>
<span class="hljs-keyword">import</span> { createInertiaApp } <span class="hljs-keyword">from</span> <span class="hljs-string">'@inertiajs/vue3'</span>
<span class="hljs-keyword">import</span> { resolvePageComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'laravel-vite-plugin/inertia-helpers'</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'../css/app.css'</span>

createInertiaApp({
...
</code></pre>
<h2 id="heading-time-to-play">Time to play</h2>
<h3 id="heading-just-to-see-if-it-works">Just to see if it works</h3>
<p>To do so, we will use a simple component taken from <a target="_blank" href="https://tailwindui.com">Tailwind UI</a>, and we replace the template part of our Index Page with this:</p>
<p><strong>/resources/js/Pages/Index.vue</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-white"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"relative isolate px-6 pt-14 lg:px-8"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-2xl py-32 sm:py-48 lg:py-56"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-4xl font-bold tracking-tight text-gray-900 sm:text-6xl"</span>&gt;</span>Data to enrich your online business<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-6 text-lg leading-8 text-gray-600"</span>&gt;</span>Anim aute id magna aliqua ad ad non deserunt sunt. Qui irure qui lorem cupidatat commodo. Elit sunt amet fugiat veniam occaecat fugiat aliqua.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-10 flex items-center justify-center gap-x-6"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"</span>&gt;</span>Get started<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-semibold leading-6 text-gray-900"</span>&gt;</span>Learn more <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span>&gt;</span>→<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<p>If Vite is started you just have to save and have a look at your browser to see</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681482311289/6620c34b-a8e0-41c3-a8d7-d46322269866.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-why-not-add-some-logic-to-play-around">Why not add some logic to play around</h3>
<p>At this time we have a static Vue application, maybe we could use some data from our Laravel Controller and play with CSS classes.</p>
<p>In our Laravel Controller, we will compute a <code>darkMode</code> random boolean that we will use on our Page.</p>
<blockquote>
<p>The Inertia render function takes a second parameter which is an associative array that will be passed as Vue props in the Page.</p>
</blockquote>
<p><strong>/app/Http/Controllers/IndexController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke</span>(<span class="hljs-params"></span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Index'</span>, [
            <span class="hljs-string">'darkMode'</span> =&gt; (<span class="hljs-keyword">bool</span>)random_int(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>),
        ]);
    }
}
</code></pre>
<p>And now on our Page, we register our <code>darkMode</code> prop (as a Boolean) in our component props and use it in the first <code>div</code> of the template to alternatively set its class to <code>bg-gray-600</code> or <code>bg-white</code>.</p>
<p><strong>/resources/views/Pages/Index.vue</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span>&gt;</span><span class="javascript">
interface Props {
  <span class="hljs-attr">darkMode</span>: boolean
}

<span class="hljs-keyword">const</span> props = defineProps&lt;Props&gt;()
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">:class</span>=<span class="hljs-string">"darkMode ? 'bg-gray-600' : 'bg-white'"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"relative isolate px-6 pt-14 lg:px-8"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-2xl py-32 sm:py-48 lg:py-56"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-4xl font-bold tracking-tight text-gray-900 sm:text-6xl"</span>&gt;</span>Data to enrich your online business<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-6 text-lg leading-8 text-gray-600"</span>&gt;</span>Anim aute id magna aliqua ad ad non deserunt sunt. Qui irure qui lorem cupidatat commodo. Elit sunt amet fugiat veniam occaecat fugiat aliqua.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-10 flex items-center justify-center gap-x-6"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"</span>&gt;</span>Get started<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-semibold leading-6 text-gray-900"</span>&gt;</span>Learn more <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span>&gt;</span>→<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<p>If we go back to our browser, we can now either see this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681482716995/51ac8b01-b75a-46ac-ba82-e5b0071f1bf8.png" alt class="image--center mx-auto" /></p>
<p>or this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681482758073/2b1294a7-8fbd-49ae-a120-be4f4950ecef.png" alt class="image--center mx-auto" /></p>
<hr />
<p><strong>All is now set to build the front-end of our application, in the next article we will prepare the back-end</strong></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Set up Inertia, Vite, Vue3, TypeScript / Build our first Page]]></title><description><![CDATA[Install the front-end tools: Inertia client side, Vite, Vue 3 with Composition API and TypeScript]]></description><link>https://tech.codivores.com/ltivt-2-inertia-vite-vue3-typescript</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-2-inertia-vite-vue3-typescript</guid><category><![CDATA[Vue.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Inertia.js]]></category><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 15 Jul 2021 17:03:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627665008142/oVypqiw66.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 14, 2023</strong></p>
</blockquote>
<h2 id="heading-front-end-tools-installation">Front-end tools installation</h2>
<p>Laravel comes with a default <code>package.json</code> file to build the front-end assets and already integrates Vite and the Laravel Vite packages.</p>
<p>We can now install all the needed dependencies via <a target="_blank" href="https://yarnpkg.com">yarn</a>, but you can of course use <a target="_blank" href="https://www.npmjs.com">npm</a> if you prefer.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Vue 3</span>
yarn add vue

<span class="hljs-comment"># Vite plugin Vue</span>
yarn add vite @vitejs/plugin-vue --dev

<span class="hljs-comment"># TypeScript</span>
yarn add typescript --dev

<span class="hljs-comment"># Inertia Vue 3 adapter (with @inertiajs/core and axios as a dependency)</span>
yarn add @inertiajs/vue3
</code></pre>
<h2 id="heading-configurations">Configurations</h2>
<h3 id="heading-inertia">Inertia</h3>
<p>We need a TypeScript file to boot our Inertia application, so let's create <code>app.ts</code> file in <code>/resources/js/</code> (you can rename the previous default <code>app.js</code> - or name it like you want and adapt the other files accordingly - and delete the <code>bootstrap.js</code> file).</p>
<p>You can refer to the <a target="_blank" href="https://inertiajs.com/client-side-setup">official documentation</a> for more details.</p>
<p>For an easy start, we will just create and mount a basic Vue / Inertia app:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createApp, h, type DefineComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>
<span class="hljs-keyword">import</span> { createInertiaApp } <span class="hljs-keyword">from</span> <span class="hljs-string">'@inertiajs/vue3'</span>
<span class="hljs-keyword">import</span> { resolvePageComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'laravel-vite-plugin/inertia-helpers'</span>

createInertiaApp({
  <span class="hljs-attr">resolve</span>: <span class="hljs-keyword">async</span> (name: string) =&gt; {
    <span class="hljs-keyword">let</span> page = <span class="hljs-keyword">await</span> resolvePageComponent(<span class="hljs-string">`../views/Pages/<span class="hljs-subst">${name}</span>.vue`</span>, <span class="hljs-keyword">import</span>.meta.glob&lt;DefineComponent&gt;(<span class="hljs-string">'../views/Pages/**/*.vue'</span>))

    <span class="hljs-keyword">return</span> page
  },
  setup({ el, App, props, plugin }) {
    createApp({ <span class="hljs-attr">render</span>: <span class="hljs-function">() =&gt;</span> h(App, props) })
      .use(plugin)
      .mount(el)
  },
})
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Import Vue and Inertia packages</p>
</li>
<li><p>Create the application, looking for Pages Vue Components <em>(that replace standard Laravel Blade files)</em> in <code>/views/Pages</code> when rendering from Laravel Controller</p>
</li>
</ul>
<h3 id="heading-vite">Vite</h3>
<p>Laravel comes with a default <code>vite.config.ts</code> file in our project root folder with laravel plugin configured that we are going to edit:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>;
<span class="hljs-keyword">import</span> laravel <span class="hljs-keyword">from</span> <span class="hljs-string">'laravel-vite-plugin'</span>;
<span class="hljs-keyword">import</span> vue <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-vue'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    <span class="hljs-attr">plugins</span>: [
        laravel({
            <span class="hljs-attr">input</span>: [<span class="hljs-string">'resources/css/app.css'</span>, <span class="hljs-string">'resources/js/app.ts'</span>],
            <span class="hljs-attr">refresh</span>: <span class="hljs-literal">true</span>,
        }),
        vue({
            <span class="hljs-attr">template</span>: {
                <span class="hljs-attr">transformAssetUrls</span>: {
                    <span class="hljs-comment">// The Vue plugin will re-write asset URLs, when referenced</span>
                    <span class="hljs-comment">// in Single File Components, to point to the Laravel web</span>
                    <span class="hljs-comment">// server. Setting this to `null` allows the Laravel plugin</span>
                    <span class="hljs-comment">// to instead re-write asset URLs to point to the Vite</span>
                    <span class="hljs-comment">// server instead.</span>
                    <span class="hljs-attr">base</span>: <span class="hljs-literal">null</span>,

                    <span class="hljs-comment">// The Vue plugin will parse absolute URLs and treat them</span>
                    <span class="hljs-comment">// as absolute paths to files on disk. Setting this to</span>
                    <span class="hljs-comment">// `false` will leave absolute URLs un-touched so they can</span>
                    <span class="hljs-comment">// reference assets in the public directory as expected.</span>
                    <span class="hljs-attr">includeAbsolute</span>: <span class="hljs-literal">false</span>,
                },
            },
        }),
    ],
});
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Import Vite and its Vue 3 SFC plugin</p>
</li>
<li><p>Define the configuration (<a target="_blank" href="https://vitejs.dev/config">Official Documentation</a>)</p>
<ul>
<li><p><code>plugins</code>:</p>
<ul>
<li><p><code>laravel</code>: adapt the location of the application entry point</p>
</li>
<li><p><code>vue</code>: use the Vite Vue plugin</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-typescript">TypeScript</h3>
<p>We create a <code>tsconfig.json</code> in our project root folder:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"ESNext"</span>,
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"Node"</span>,
    <span class="hljs-attr">"resolveJsonModule"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"useDefineForClassFields"</span>: <span class="hljs-literal">true</span>,

    <span class="hljs-comment">// Required in Vue projects</span>
    <span class="hljs-attr">"jsx"</span>: <span class="hljs-string">"preserve"</span>,

    <span class="hljs-comment">// `"noImplicitThis": true` is part of `strict`</span>
    <span class="hljs-comment">// Added again here in case some users decide to disable `strict`.</span>
    <span class="hljs-comment">// This enables stricter inference for data properties on `this`.</span>
    <span class="hljs-attr">"noImplicitThis"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,

    <span class="hljs-comment">// Required in Vite</span>
    <span class="hljs-attr">"isolatedModules"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-comment">// For `&lt;script setup&gt;`</span>
    <span class="hljs-comment">// See &lt;https://devblogs.microsoft.com/typescript/announcing-typescript-4-5-beta/#preserve-value-imports&gt;</span>
    <span class="hljs-attr">"preserveValueImports"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-comment">// Enforce using `import type` instead of `import` for types</span>
    <span class="hljs-attr">"importsNotUsedAsValues"</span>: <span class="hljs-string">"error"</span>,

    <span class="hljs-comment">// A few notes:</span>
    <span class="hljs-comment">// - Vue 3 supports ES2016+</span>
    <span class="hljs-comment">// - For Vite, the actual compilation target is determined by the</span>
    <span class="hljs-comment">//   `build.target` option in the Vite config.</span>
    <span class="hljs-comment">//   So don't change the `target` field here. It has to be</span>
    <span class="hljs-comment">//   at least `ES2020` for dynamic `import()`s and `import.meta` to work correctly.</span>
    <span class="hljs-comment">// - If you are not using Vite, feel free to override the `target` field.</span>
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"ESNext"</span>,

    <span class="hljs-comment">// Recommended</span>
    <span class="hljs-attr">"esModuleInterop"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"forceConsistentCasingInFileNames"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-comment">// See &lt;https://github.com/vuejs/vue-cli/pull/5688&gt;</span>
    <span class="hljs-attr">"skipLibCheck"</span>: <span class="hljs-literal">true</span>,

    <span class="hljs-attr">"types"</span>: [<span class="hljs-string">"vite/client"</span>, <span class="hljs-string">"node"</span>],

    <span class="hljs-attr">"baseUrl"</span>: <span class="hljs-string">"."</span>,
    <span class="hljs-attr">"paths"</span>: {
      <span class="hljs-attr">"@/*"</span>: [<span class="hljs-string">"resources/*"</span>]
    },
    <span class="hljs-attr">"include"</span>: [
      <span class="hljs-string">"resources/js/**/*.ts"</span>,
      <span class="hljs-string">"resources/js/**/*.d.ts"</span>,
      <span class="hljs-string">"resources/**/*.vue"</span>
    ]
  }
}
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Use default compiler options given by Vue</p>
</li>
<li><p>Defines the include folders: all <code>.ts</code>, <code>.d.ts</code> and <code>.vue</code> files in our <code>resources</code> folders</p>
</li>
</ul>
<h3 id="heading-scripts-definition">Scripts definition</h3>
<p>All the configuration is set, let's have a look at the Vite scripts in our <code>package.json</code></p>
<pre><code class="lang-json">    <span class="hljs-string">"scripts"</span>: {
        <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"vite"</span>,
        <span class="hljs-attr">"build"</span>: <span class="hljs-string">"vite build"</span>
    },
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p><code>dev</code>: start Vite server</p>
</li>
<li><p><code>build</code>: build production bundles</p>
</li>
</ul>
<p>Of course, you can name them like you want and adapt the scripts according to your build process.</p>
<p>We can now start our development environment:</p>
<pre><code class="lang-bash">yarn dev
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681468373313/51926191-6ed1-40e2-9a7d-0a7ed7bc632f.png" alt /></p>
<p>Or build for production:</p>
<pre><code class="lang-bash">yarn build
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681468483638/04f0b161-b704-4dcb-bec6-fc1aaf4ba14a.png" alt /></p>
<h2 id="heading-root-view-set-up">Root View set up</h2>
<p>To integrate Inertia and load our assets on the first page visit, we need a standard view Blade file. So we create <code>app.blade.php</code> in <code>/resources/views/</code> folder (you can use and rename the default <code>welcome.blade.php</code>).</p>
<blockquote>
<p><code>app.blade.php</code> is the default view used by Inertia, you can change it in the Inertia Middleware or call <code>Inertia::setRootView()</code> in your code.</p>
</blockquote>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"{{ str_replace('_', '-', app()-&gt;getLocale()) }}"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span>&gt;</span>
        @vite('resources/js/app.ts')
        @inertiaHead
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        @inertia
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>What it does</strong></p>
<ul>
<li><p>Add the <code>@vite()</code> Blade directive in the <code>head</code> to reference our Vite entry point</p>
</li>
<li><p>Add the <code>@inertiaHead</code> Blade directive in the <code>head</code></p>
</li>
<li><p>Add the <code>@inertia()</code> Blade directive in the <code>body</code></p>
</li>
</ul>
<h2 id="heading-time-to-play-and-display-our-first-page">Time to play and display our first Page</h2>
<p>All that remains to do is:</p>
<ul>
<li><p>Create a Laravel Controller with its route</p>
</li>
<li><p>Create a Vue Page</p>
</li>
</ul>
<h3 id="heading-laravel">Laravel</h3>
<p>We will create a simple Controller, its only task is to render the Index Page (that Inertia will resolve in our <code>/resources/js/app.ts</code> and that will look for <code>/resources/views/Pages/Index.vue</code> file).</p>
<p><strong>/app/Http/Controllers/IndexController.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Inertia</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Inertia</span>\<span class="hljs-title">Response</span> <span class="hljs-title">as</span> <span class="hljs-title">InertiaResponse</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke</span>(<span class="hljs-params"></span>): <span class="hljs-title">InertiaResponse</span>
    </span>{
        <span class="hljs-keyword">return</span> Inertia::render(<span class="hljs-string">'Index'</span>);
    }
}
</code></pre>
<p><strong>/routes/web.php</strong></p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">IndexController</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;

Route::get(<span class="hljs-string">'/'</span>, IndexController::class)-&gt;name(<span class="hljs-string">'index'</span>);
</code></pre>
<h3 id="heading-vue">Vue</h3>
<p>We will start displaying a welcome message and write something in the console.</p>
<p><strong>/resources/views/Pages/Index.vue</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> { defineComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineComponent({
  setup() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Page - Index'</span>)
  },
})
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Or with the SFC <code>&lt;script setup&gt;</code> (compile-time syntactic sugar for using Composition API inside Single File Components: <a target="_blank" href="https://vuejs.org/api/sfc-script-setup.html">https://vuejs.org/api/sfc-script-setup.html</a>)</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Page - Index'</span>)
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<h3 id="heading-ruuuuuun">RUUUUUUN</h3>
<p>Start Vite</p>
<pre><code class="lang-bash">yarn dev
</code></pre>
<p>Go to the web root of your project in a browser (probably <code>http://localhost</code>)</p>
<p>and...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681474424942/ae4ba4a4-fd14-43f8-beee-c42fa10ce617.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-and-maybe-should-we-validate-the-production-build">And maybe should we validate the production build</h3>
<p>First we build our assets.</p>
<pre><code class="lang-bash">yarn build
</code></pre>
<p>Now refresh your browser and you can see that the production JavaScript files are loaded</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681474474730/7a85c63d-9425-4d70-9945-4d2a03e06c3d.png" alt class="image--center mx-auto" /></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Set up Laravel with Inertia]]></title><description><![CDATA[First steps of the project, install Laravel and Inertia server side]]></description><link>https://tech.codivores.com/ltivt-1-laravel-with-inertia</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-1-laravel-with-inertia</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Inertia.js]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Thu, 15 Jul 2021 13:35:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627664994987/ZCHKnMW8s.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 13, 2023</strong></p>
</blockquote>
<h2 id="heading-install-laravel">Install Laravel</h2>
<p>If you've never worked on a Laravel project, you can find all the ways to install it and start a new project on the <a target="_blank" href="https://laravel.com/docs/10.x/installation#your-first-laravel-project">official documentation</a>, and there are many good tutorials you can find depending on your development environment.</p>
<p>Here we work with Docker containers and use Composer to install Laravel in our project folder.</p>
<pre><code class="lang-php">composer create-project laravel/laravel app
</code></pre>
<p>That will create the base structure of the project, install all the dependencies and set the default configuration (we generally make a first Git commit after the fresh install).</p>
<h2 id="heading-install-inertia-server-side">Install Inertia - Server Side</h2>
<h3 id="heading-dependencies-installation">Dependencies installation</h3>
<p>Inertia comes as a Laravel package that can be installed via Composer. You can refer to the official setup on the <a target="_blank" href="https://inertiajs.com/server-side-setup">official documentation</a>.</p>
<pre><code class="lang-plaintext">composer require inertiajs/inertia-laravel
</code></pre>
<h3 id="heading-middleware-set-up">Middleware set up</h3>
<p>To have Inertia intercept the application requests and do its magic (shared data, assets versioning), we need to add a middleware.</p>
<p>This can be done by executing an artisan command which will publish the <code>HandleInertiaRequests</code> middleware in our middleware folder <code>/app/HTTP/Middleware</code>.</p>
<pre><code class="lang-plaintext">php artisan inertia:middleware
</code></pre>
<p>Once created, we need to register it manually in our <code>/app/Http/Kernel.php</code> file, in the last position of our web route middleware groups.</p>
<pre><code class="lang-plaintext">    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' =&gt; [
            // ...

            \App\Http\Middleware\HandleInertiaRequests::class,
        ],
    ];
</code></pre>
<p><em>Of course, we need more steps to see Inertia in action, but we now have it ready to handle our application requests.</em></p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[The Why and the What]]></title><description><![CDATA[Our new CMS stack: Laravel, Twill, Inertia, Vue 3 with Composition API and TypeScript, Vite and Tailwind]]></description><link>https://tech.codivores.com/ltivt-0-why-and-what</link><guid isPermaLink="true">https://tech.codivores.com/ltivt-0-why-and-what</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Twill]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Wed, 14 Jul 2021 16:05:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627664958463/OZFoZoVypW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>Updated version for Laravel 10 / Twill 3 on Apr 13, 2023</strong></p>
<p>We are not regular writers and even less in english, so please accept our apologies in advance! (and we encourage your feedback)</p>
</blockquote>
<p>After some years building Laravel based applications and using more and more Vue.js for the front-end, we are now updating our stack for CMS projects, trying to bring together the best tools and practices to provide the best experience for our clients, our clients' clients and of course us as developers.</p>
<p>For this first article of the serie, we will introduce the stack</p>
<ul>
<li><p>Laravel</p>
</li>
<li><p>Twill</p>
</li>
<li><p>Inertia</p>
</li>
<li><p>Vue 3 with Composition API and TypeScript</p>
</li>
<li><p>Vite</p>
</li>
<li><p>Tailwind</p>
</li>
</ul>
<h2 id="heading-laravel">Laravel</h2>
<blockquote>
<p>Website: <a target="_blank" href="https://laravel.com">https://laravel.com</a></p>
<p>Documentation: <a target="_blank" href="https://laravel.com/docs/10.x">https://laravel.com/docs/10.x</a></p>
<p>Git: <a target="_blank" href="https://github.com/laravel/laravel">https://github.com/laravel/laravel</a></p>
</blockquote>
<p>We are mainly PHP developers and we cannot imagine using another framework these days. But if you are here, we guess your share the same feelings (let us know if not, we can provide some insights).</p>
<h2 id="heading-twill">Twill</h2>
<blockquote>
<p>Website: <a target="_blank" href="https://twill.io">https://twill.io</a></p>
<p>Documentation: <a target="_blank" href="https://twillcms.com/docs/">https://twillcms.com/docs/</a></p>
<p>Git: <a target="_blank" href="https://github.com/area17/twill">https://github.com/area17/twill</a></p>
</blockquote>
<p>Despite the huge Laravel ecosystem, it's not easy to find a package that offers CMS features with a good UX for our clients. We use Twill since 2020 and built dozens of projects, we (and our clients) are very satisfied with the functionalities and flexibility this open source package offers:</p>
<ul>
<li><p>No front-end: that could scare you a little bit at first, but it allows you to use it with Laravel or as a headless CMS</p>
</li>
<li><p>CLI to create needed files to handle new content (model, admin controller, form, routing, admin navigation)</p>
</li>
<li><p>Multi-language in a very easy way to work with</p>
</li>
<li><p>Content publication status and scheduling (draft, start and end dates), responsive preview, revisions with visual comparison</p>
</li>
<li><p>Media library with built-in <a target="_blank" href="https://glide.thephpleague.com">Glide</a> integration (smart cropping and profiles)</p>
</li>
<li><p>Block editor, repeaters for quick and flexible content creation</p>
</li>
<li><p>Dashboard you can customize</p>
</li>
</ul>
<h2 id="heading-inertia">Inertia</h2>
<blockquote>
<p>Website / Documentation: <a target="_blank" href="https://inertiajs.com">https://inertiajs.com</a></p>
<p>Git: <a target="_blank" href="https://github.com/inertiajs">https://github.com/inertiajs</a></p>
</blockquote>
<p>After some small projects made with Inertia, we are now confident this back-end/front-end wrapper (hard to find a good definition) is a game changer, allowing us to build our back-end as a standard Laravel application and make it a SPA with Vue.js page components without worrying about Ajax calls, shared data, ...</p>
<h2 id="heading-vue-3-typescript">Vue 3 / TypeScript</h2>
<blockquote>
<p>Website: <a target="_blank" href="https://vuejs.org/">https://vuejs.org/</a></p>
<p>Documentation: <a target="_blank" href="https://vuejs.org/guide">https://vuejs.org/guide</a></p>
<p>Git: <a target="_blank" href="https://github.com/vuejs/">https://github.com/vuejs/</a></p>
</blockquote>
<p>After some Vue 2 / Nuxt projects, it's time to move forward and go for Vue 3, and if we are going to use it, we should do it with the best approach, meaning</p>
<ul>
<li><p>Composition API: better and cleaner code definition, reuse and sharing</p>
</li>
<li><p>TypeScript: good support for Composition API, and also better and cleaner code</p>
</li>
</ul>
<h2 id="heading-vite">Vite</h2>
<blockquote>
<p>Website: <a target="_blank" href="https://vitejs.dev">https://vitejs.dev</a></p>
<p>Documentation: <a target="_blank" href="https://vitejs.dev/guide">https://vitejs.dev/guide</a></p>
<p>Git: <a target="_blank" href="https://github.com/vitejs/vite">https://github.com/vitejs/vite</a></p>
</blockquote>
<p>Before version 10, Laravel came natively with <a target="_blank" href="https://laravel.com/docs/8.x/mix">Laravel Mix</a> based on <a target="_blank" href="https://webpack.js.org">Webpack</a> and we used it a lot. But we are not big fans of Webpack (surely a lack of investment on our part), and on big projects, we got some big build times, slow Hot Module Replacement and big outputs.</p>
<p>Then appeared Vite in 2020 which seemed to provide faster development experience with Hot Module Replacement and Rollup for production builds. So, we decided to give it a try... and became the default asset bundling tool in Laravel 10!</p>
<h2 id="heading-tailwind">Tailwind</h2>
<blockquote>
<p>Website: <a target="_blank" href="https://tailwindcss.com">https://tailwindcss.com</a></p>
<p>Documentation: <a target="_blank" href="https://tailwindcss.com/docs">https://tailwindcss.com/docs</a></p>
<p>Git: <a target="_blank" href="https://github.com/tailwindlabs/tailwindcss">https://github.com/tailwindlabs/tailwindcss</a></p>
</blockquote>
<p>Tailwind is a utility-first CSS framework. There are Pros and Cons and we will not be arguing that here. We use it for many years now, it continues to improve (responsive, dark mode, small size production builds purging unused CSS with <a target="_blank" href="https://postcss.org">PostCSS</a>), so why change!</p>
<hr />
<blockquote>
<p>We'll do our best to provide source code of the serie on <a target="_blank" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">GitHub</a></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind">https://github.com/Codivores/tutorial-laravel-twill-inertia-vue3-vite-tailwind</a></div>
]]></content:encoded></item><item><title><![CDATA[Laravel - Health Check]]></title><description><![CDATA[Exemple d’un contrôleur simple de surveillance d‘une application Laravel]]></description><link>https://tech.codivores.com/laravel-health-check</link><guid isPermaLink="true">https://tech.codivores.com/laravel-health-check</guid><category><![CDATA[Laravel]]></category><category><![CDATA[monitoring]]></category><dc:creator><![CDATA[Codivores]]></dc:creator><pubDate>Fri, 25 Jun 2021 12:32:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626291962988/zI6ftFelM.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ce n'est pas une surprise, il existe de nombreux packages Laravel permettant de contrôler la santé de votre application : accès à la base de données, écriture dans des dossiers de stockage, validité du certificat SSL, services Mail, Redis, ... et qui peuvent être étendus pour créer des contrôles spécifiques à votre application.</p>
<p>Mais pour des petits projets avec peu de fonctionnalités, ces packages nous semblent légèrement surdimensionnés (toujours un peu de scrupules à installer un package pour n'en utiliser qu'une infime partie).</p>
<h2 id="ok-vous-faites-quoi-alors-pour-les-petits-projets">Ok, vous faîtes quoi alors pour les petits projets ?</h2>
<p>Pour ceux-là, nous utilisons généralement un simple contrôleur Laravel qui va vérifier que l'accès à la base de données fonctionne et que l'écriture dans un dossier de stockage de l'application est possible.</p>
<p><strong>/app/Http/Controllers/HealthcheckController.php</strong></p>
<pre><code><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">DB</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Storage</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HealthcheckController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> $displayError = <span class="hljs-literal">false</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params"></span>): \<span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>
    </span>{
        <span class="hljs-keyword">try</span> {
            $healthcheck =
                <span class="hljs-keyword">$this</span>-&gt;checkDatabase()
                &amp;&amp; <span class="hljs-keyword">$this</span>-&gt;checkStorage();

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;makeResponse($healthcheck);
        } <span class="hljs-keyword">catch</span> (\<span class="hljs-built_in">Exception</span> $e) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;makeResponse(<span class="hljs-literal">false</span>, $e-&gt;getMessage());
        }
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeResponse</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> $healthcheck = <span class="hljs-literal">false</span>, <span class="hljs-keyword">string</span> $message = <span class="hljs-string">''</span></span>): \<span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Response</span>
    </span>{
        <span class="hljs-keyword">return</span> response($message, ($healthcheck) ? <span class="hljs-number">200</span> : <span class="hljs-number">500</span>);
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkDatabase</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $table = <span class="hljs-literal">null</span></span>): <span class="hljs-title">bool</span>
    </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-literal">null</span> === $table) {
            $table = <span class="hljs-string">'migrations'</span>;
        }

        <span class="hljs-keyword">try</span> {
            DB::table($table)-&gt;take(<span class="hljs-number">1</span>)-&gt;get();
        } <span class="hljs-keyword">catch</span> (\<span class="hljs-built_in">Exception</span> $e) {
            report($e);
            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">$this</span>-&gt;displayError) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> \<span class="hljs-built_in">Exception</span>($e);
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            }
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkStorage</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $disk = <span class="hljs-string">'local'</span></span>): <span class="hljs-title">bool</span>
    </span>{
        <span class="hljs-keyword">try</span> {
            $filename = <span class="hljs-string">'healthcheck.txt'</span>;
            $date = now()-&gt;toDatetimeString();

            <span class="hljs-keyword">if</span> (!Storage::disk($disk)-&gt;put($filename, $date)) {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            }

            <span class="hljs-keyword">if</span> (!Storage::disk($disk)-&gt;delete($filename)) {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            }
        } <span class="hljs-keyword">catch</span> (\<span class="hljs-built_in">Exception</span> $e) {
            report($e);
            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">$this</span>-&gt;displayError) {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> \<span class="hljs-built_in">Exception</span>($e);
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            }
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
}
</code></pre><blockquote>
<p>Les erreurs sont traitées par le logger par défaut de Laravel (par défaut, écriture dans le fichier <code>laravel...log</code>) et aucune information d'erreur n'est renvoyée par le contrôleur, simplement un code HTTP 500 au lieu de 200. Si vous souhaitez que le contrôleur affiche les erreurs, passez le booléen <code>$displayError</code> à <code>true</code>.</p>
</blockquote>
<p>Pour rendre le contrôleur accessible (<em>https://monsite.com/healthcheck</em>), pensez à ajouter la route Web associée (l'appel à la fonction <code>name</code> est facultatif) :</p>
<p><strong>/routes/web.php</strong></p>
<pre><code><span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">HealthcheckController</span>;

Route::get(<span class="hljs-string">'/healthcheck'</span>, [HealthcheckController::class, <span class="hljs-string">'check'</span>])-&gt;name(<span class="hljs-string">'healthcheck'</span>);
</code></pre><h2 id="et-maintenant-vous-en-faites-quoi-de-votre-health-check">Et maintenant, vous en faîtes quoi de votre Health Check ?</h2>
<p>Avoir une URL accessible sur son application c'est bien, mais à moins que vous n'ayez envie de passer votre temps devant votre navigateur à rafraîchir la page ou de développer un script d'appel de l'URL qui va ensuite vous notifier par le moyen de votre choix, il existe là aussi de nombreuses solutions qui peuvent s'en charger pour vous :</p>
<ul>
<li>Configuration d'une URL de Health Check qui va être appelée à intervalle régulier. D'autres types qu'un appel HTTP sont généralement possibles : API, DNS, ping, réponse sur un port donné, test sur le contenu de la réponse, …</li>
<li>Notification en cas de problème : e-mail, SMS, notification Push, Slack, Twitter, Webhooks, …</li>
<li>Informations détaillées sur la santé de l'application et de l'hébergement : temps de réponse, de rendu de la page, historique des incidents, …</li>
</ul>
<p>Actuellement, nous utilisons la solution <a target="_blank" href="https://uptimerobot.com">UptimeRobot </a> qui propose une offre gratuite (jusqu'à 50 contrôleurs, notification par e-mail uniquement) suffisante pour de la surveillance de premier niveau. Vous pourrez en plus créer des pages publiques de statut, personnalisables avec la sélection des contrôleurs de votre choix à afficher, la protection par mot de passe, que vous pourrez ensuite afficher sur un écran en mode tableau de bord, communiquer à vos équipes ou vos clients.</p>
<p><strong>Exemple de page publique de statut UptimeRobot</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1626265359150/a_NGhG5lc.png" alt="image.png" /></p>
]]></content:encoded></item></channel></rss>