Last active
September 2, 2022 20:26
-
-
Save mauricius/1fa68b23f0b3e8cb374cc7d02d00a3e7 to your computer and use it in GitHub Desktop.
Fragment rendering in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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