Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay

JeffreyWay/web.php

Created Jul 17, 2020
Embed
What would you like to do?
Array Filtering + Casting Demo
<?php
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/names', function () {
$names = collect(['Jack', 'Jill', 'Bill', 'Chuck', 'Jane', 'June', 'Jim']);
if ($letter = request('firstLetter', 'J')) {
// This won't work the way you expect, without calling ->values().
return $names->filter(fn($name) => Str::startsWith($name, $letter));
}
return $names;
});
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Filter Gotcha</title>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"
defer
></script>
</head>
<body>
<div
x-data="{
names: [],
letter: 'A',
fetchNames() {
fetch('/names?firstLetter=' + this.letter)
.then(response => response.json())
.then(result => this.names = result);
}
}"
x-init="fetchNames"
>
<select x-model="letter" @change="fetchNames">
@foreach (range('A', 'Z') as $letter)
<option value="{{ $letter }}">{{ $letter }}</option>
@endforeach
</select>
<ul>
<template x-for="(name, index) in names" :key="index">
<li x-text="name"></li>
</template>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment