Squire: Static Eloquent Model Library
Published on by Dan Harrin
Squire is a library of prebuilt static Eloquent models for common fixture data. It provides information about countries, currencies, airports, and more to your Laravel app, without the use of a third-party API.
Setup is simple – just install the model packages that you need in your app, and you’re ready to go. Squire comes out of the box with queryable Eloquent models, validation rules, and full localization support.
Squire is built upon the principles demonstrated in Caleb Porzio’s Sushi package: all models are served by their own SQLite databases, and cached.
Building a Country Select Input
We’re going to create a country select input using data from Squire. Let’s install the Squire\Models\Country
model in English:
composer require squirephp/countries-en
Tip: all Squire models are translatable. Squire can automatically serve the correct data based on your user’s locale. To try it out, also install the squirephp/countries-fr
package, and notice how French users will be served in the correct language.
To keep things simple, use Blade to query the Country model and render our select options:
<select name="country"> @foreach (Squire\Models\Country::orderBy('name')->get() as $country) <option value="{{ $country->id }}">{{ $country->name }} {{ $country->flag }}</option> @endforeach</select>
Validate the input to ensure that a valid country has been selected in a controller:
use Squire\Rules\Country; $request->validate([ 'country' => ['required', 'string', new Country],]);
You’re able to use conventional Eloquent relationships between Squire and non-Squire models. Let’s set up a country
relationship for the country_id
column on the App\Models\User
model:
use Squire\Models\Country; public function country(){ return $this->belongsTo(Country::class);}
Save the selected country to $user
in your controller:
$user->country()->associate($request->country); $user->save();
Rounding Off
Squire has the capability to replace many third-party APIs in your Laravel app, cutting costs and improving performance.
The ecosystem is constantly expanding as new models and translations are submitted and published by the community. If you see anything missing, feel free to open a feature discussion or pull request in the repository, or release your own Squire package.
If you have any questions, feel free to tweet me @danjharrin and I’ll do my best to respond. If you love Squire, sponsoring me on GitHub ensures I can dedicate time to maintaining and improving the package.