Skip to content

Your First renderBlade Block ​

Goal: an expandable block. Clicking "Refresh" replaces the whole HTML, and the expanded state survives. No JavaScript.

1. Make the controller callable ​

php
namespace App\Http\Controllers;

use App\Traits\CanRenderCallSafely;
use Illuminate\Contracts\View\View;

class HelloController extends Controller
{
    use CanRenderCallSafely;

    public function index(): View
    {
        return view('pages.hello');
    }

    public function renderCallSafely(array $params = [], string $method = 'components'): View
    {
        return view('partials.hello-box', ['renderedAt' => now()->format('H:i:s')]);
    }
}

CanRenderCallSafely is the allow list: renderBlade refuses any controller that doesn't use this trait.

2. The fragment ​

resources/views/partials/hello-box.blade.php:

blade
<p>Rendered on the server at: {{ $renderedAt }}</p>

<button type="button" data-state-toggle="open">Expand / collapse</button>

<div data-state-show="open">
    Whether this is expanded lives in client state, not in the DOM.
</div>

3. The page ​

resources/views/pages/hello.blade.php:

blade
<section @renderObject('helloBox', ['render', 'state:read', 'state:write'])
         data-state-init="open=false">

    <div id="hello-box">
        @include('partials.hello-box', ['renderedAt' => now()->format('H:i:s')])
    </div>

    <button type="button"
            @renderBlade(\App\Http\Controllers\HelloController::class, 'components', [], '#hello-box')>
        Refresh
    </button>
</section>
  • @renderObject declares that this block may render and read/write state. The name helloBox is the namespace.
  • data-state-init only writes keys that don't exist yet, so re-rendering never overwrites what the user did.
  • @renderBlade outputs data-cg-event="renderBlade" and the target selector.

4. Try it ​

  1. Click "Expand" and the content appears.
  2. Click "Refresh". The time changes (the HTML was replaced), and the content is still expanded.
  3. Paste this into the console:
js
document.addEventListener('cg:state', e => console.log(e.detail.key, '→', e.detail.value));

Every toggle prints helloBox:open → true/false.

Why it works ​

Next: the tutorials, or dig into renderBlade concepts.