Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created July 17, 2020 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JeffreyWay/0b42598ef5c2ccb9a2993c1087261fe8 to your computer and use it in GitHub Desktop.
Save JeffreyWay/0b42598ef5c2ccb9a2993c1087261fe8 to your computer and use it in GitHub Desktop.
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