Skip to content

Instantly share code, notes, and snippets.

@mauricius
Last active September 2, 2022 20:26
Show Gist options
  • Save mauricius/1fa68b23f0b3e8cb374cc7d02d00a3e7 to your computer and use it in GitHub Desktop.
Save mauricius/1fa68b23f0b3e8cb374cc7d02d00a3e7 to your computer and use it in GitHub Desktop.
Fragment rendering in Laravel
<?php
Route::get('/', function () {
$contact = Contact::first();
return View::make('template', compact('contact'));
});
Route::delete('contacts/{id}', function ($id) {
$contact = Contact::find($id);
$contact->update(['active' => false]);
$contact->save();
return View::renderFragment('template', 'archive-ui', compact('contact'));
});
Route::patch('contacts/{id}/unarchive', function ($id) {
$contact = Contact::find($id);
$contact->update(['active' => true]);
$contact->save();
return View::renderFragment('template', 'archive-ui', compact('contact'));
});
<html>
<body>
<div hx-target="this">
@section("archive-ui")
@if($contact->archived)
<button hx-patch="/contacts/{{ $contact->id }}/unarchive">Unarchive</button>
@else
<button hx-delete="/contacts/{{ $contact->id }}">Archive</button>
@endif
@show
</div>
<h3>Contact</h3>
<p>{{ $contact->email }}</p>
</body>
</html>
<?php
use Illuminate\Support\Facades\View;
View::macro('renderFragment', function ($view, $fragment, array $data = []) {
$path = View::make($view, $data)->getPath();
$content = File::get($path);
$re = sprintf('/@section\("%s"\)(.*)@show/ms', $fragment);
preg_match($re, $content, $matches);
return Blade::render($matches[1], $data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment