-
-
Save AliAmazone/bac123ebc04d4af3b856f7d17343f8be to your computer and use it in GitHub Desktop.
Array Filtering + Casting Demo
This file contains 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\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; | |
}); | |
This file contains 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
<!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