Server fetched partial laravel
This just got me interested in using it on all my projects, as before I only knew about populating data using partial is by adding some code in the service provider and I think that it's a bit out of place.
// lets say we have this
Route::get('/', function() {
$users = App\User::inRandomOrder()->limit(5)->get();
return view('sponsorship', ['users',$users]);
});
// sponsorship.blade.php
<button>refresh</button>
<ul>
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</li>
then make it like this
// add a new route and move it there
Route::get('/', function() {
return view('sponsorship');
});
Route::get('/partials/users', function() {
$users = App\User::inRandomOrder()->limit(5)->get();
return view('_users', ['users',$users]);
});
// sponsorship.blade.php
<button onClick="fetchUsers()">refresh</button>
<ul id="js-user-target">
</li>
<script>
function fetchUsers() {
fetch('/partials/users')
.then(response => response.text())
.then(html => {
document.querySelector('#js-user-target).innerHTML = html
});
}
fetchUsers();
</script>
// _users.blade.php
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
Another way is to use a package
Lets say we have this, we have a lot of users
Route::get('/', function() {
return view('users', [
'users' => App\User::all(),
]);
});
// users.blade.php
<div>
<table>
@foreach ($users as $user)
{{ $user->name }}
@endforeach
</table>
</div>
then we do this, just like previous example
Route::get('/', function() {
return view('users');
});
Route::get('/partials/users', function() {
return view('users', [
'users' => App\User::all(),
]);
});
// users.blade.php
<div id="js-user-target">
<include-fragment src="/partials/invoices">
...loading
</include-fragment>
</div>
<script src="https://unpkg.com/@github/include-fragment-element"></script>
_users.blade.php
<table>
@foreach ($users as $user)
{{ $user->name }}
@endforeach
</table>
Also, there's another trick to add to feels like an SPA, use turbolinks
// add this in header
<script src="https://unpkg.com/turbolinks"></script>
Some gotchas fix
// make a middleware
php artisan make:middleware SetTurboLinksHeader
public function handle($request, Closure $handler) {
$response = $next($request);
$response->header('Turbolinks-Location', $request->url());
}
// in kernel.php add
SetTurbolinksHeader::class