Squire: Static Eloquent Model Library

Packages

January 15th, 2021

squire.png

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:

1composer 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:

1<select name="country">
2 @foreach (Squire\Models\Country::orderBy('name')->get() as $country)
3 <option value="{{ $country->id }}">{{ $country->name }} {{ $country->flag }}</option>
4 @endforeach
5</select>

Validate the input to ensure that a valid country has been selected in a controller:

1use Squire\Rules\Country;
2
3$request->validate([
4 'country' => ['required', 'string', new Country],
5]);

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:

1use Squire\Models\Country;
2
3public function country()
4{
5 return $this->belongsTo(Country::class);
6}

Save the selected country to $user in your controller:

1$user->country()->associate($request->country);
2
3$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.

Filed in:

Dan Harrin

TALL-stack developer. Building Filament, Envault and Squire. Co-hosting the Undefined Variable podcast.