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>@renderObjectdeclares that this block mayrenderand read/write state. The namehelloBoxis the namespace.data-state-initonly writes keys that don't exist yet, so re-rendering never overwrites what the user did.@renderBladeoutputsdata-cg-event="renderBlade"and the target selector.
4. Try it
- Click "Expand" and the content appears.
- Click "Refresh". The time changes (the HTML was replaced), and the content is still expanded.
- 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.