Learn Laravel Sushi - The array driver for Eloquent
Published on by Jason Beggs
Last week, I posted an article building an example app using Volt and Folio. In that example, I used Caleb Porzio's package, Sushi, to stub out some example data. That got me curious about what other people are using Sushi for, so I tweeted asking people what they're using it for. In this article, we'll cover the basic concepts of Sushi and a few examples of how you might use it.
What is Laravel Sushi, and how does it work?
According to the package's README, Sushi is "Eloquent's missing "array" driver." In other words, it allows you to create Eloquent models from data sources other than a database. The simplest way to use it is by providing your data as a hardcoded array right inside the Model file, setting the $rows
property. Other times, you may use the getRows
to provide dynamic data - from an API source, a CSV file, or anywhere else you choose.
So how does it actually work? Sushi takes the data you give it, creates Eloquent models, then caches them in a sqlite database. Then, you can query the data just like any standard Eloquent model.
Here's a very basic example of a Sushi model:
<?php namespace App\Models; use Sushi\Sushi; class Role extends Model{ // Add the trait use Sushi; // Provide the data as a hardcoded array protected $rows = [ ['id' => 1, 'label' => 'admin'], ['id' => 2, 'label' => 'manager'], ['id' => 3, 'label' => 'user'], ];}
Laravel Sushi States
Let's get into some real-world examples I and others have used. The most basic one I'll cover is creating a list or table of states. Ken and Facundo mentioned this use-case, but I've personally used it as well.
<?php namespace App\Models; use Sushi\Sushi; class Role extends Model{ use Sushi; protected $rows = [ [ 'id' => 1, 'name' => 'Alabama', 'abbreviation' => 'AL', ], [ 'id' => 2, 'name' => 'Alaska', 'abbreviation' => 'AK', ], [ 'id' => 3, 'name' => 'Arizona', 'abbreviation' => 'AZ', ], [ 'id' => 4, 'name' => 'Arkansas', 'abbreviation' => 'AR', ], [ 'id' => 5, 'name' => 'California', 'abbreviation' => 'CA', ], // ... ];}
Note: the 'id' column is optional. Sushi can create auto-incrementing IDs for each item, but if the items change (and the cache is busted), you're not guaranteed items will receive the same IDs they had before. If you're going to associate other data with Sushi models, it's best to provide a static ID column for each item.
Laravel Sushi for blogs, courses, and info-products
Another handy use case is for simple blogs and courses. Sometimes, as a developer, I need to store some pages for a blog or course, but I don't need the weight of a full CMS. I'd rather keep it lightweight, while at the same time having all my content stored directly in code so it can be synced via Git.
Aaron mentioned he uses this kind of setup for the blog on aaronfrancis.com. Caleb mentioned the Livewire v2 screencasts platform utilizes something similar to this:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Sushi\Sushi; class Series extends Model{ use Sushi; public function screencasts() { return $this->hasMany(Screencast::class); } public function getRows() { return [ ['id' => 1, 'order' => 1, 'title' => 'Getting Started'], ['id' => 2, 'order' => 2, 'title' => 'A Basic Form With Validation'], //... ]; }}
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Sushi\Sushi; class Screencast extends Model{ use Sushi; public function series() { return $this->belongsTo(Series::class); } public function getNextAttribute() { return static::find($this->id + 1); } public function getPrevAttribute() { return static::find($this->id - 1); } public function getDurationInSecondsAttribute() { // ... } protected $rows = [ [ 'title' => 'Installation', 'slug' => 'installation', 'description' => "Installing Livewire is so simple, this 2.5 minute video feels like overkill. Composer require, and two little lines added to your layout file, and you are fully set up and ready to rumble!", 'video_url' => 'https://vimeo.com/...', 'code_url' => 'https://github.com/...', 'duration_in_minutes' => '2:32', 'series_id' => 1, ], [ 'title' => 'Data Binding', 'slug' => 'data-binding', 'description' => "The first and most important concept to understand when using Livewire is "data binding". It's the backbone of page reactivity in Livewire, and it'll be your first introduction into how Livewire works under the hood. Mandatory viewing.", 'video_url' => 'https://vimeo.com/...',, 'code_url' => 'https://github.com/...', 'duration_in_minutes' => '9:11', 'series_id' => 1, ], // ... ];}
As you see in this example, since these are real Eloquent models, you can add relationships, getters, and helper methods just as you can on regular models.
With those models, you can query them in a controller or Livewire component just as you would a database-driven model:
$series = Series::with(['screencasts'])->orderBy('order')->get();
Then, you can loop over them in your Blade:
<div> @foreach($series as $s) <div> <h2>{{ $series->title }}</h2> <div> @foreach($series->screencasts as $screencast) <div> <h3>{{ $screencast->title }}</h3> <p>{{ $screencast->description }}</p> </div> @endforeach </div> </div> @endforeach</div>
You can even use Laravel's route model binding to automatically query Sushi models:
Route::get('/screencasts/{screencast:slug}');
Caleb and I use a very similar approach to storing the components for Alpine Components. We use route model binding for the routes, then Blade views to show the details for each component.
Inside the Blade views, we loop over the component's variants and use @include($variant->view)
to include separate hard-coded Blade views that have the actual code for the component.
<?php namespace App\Models; use App\Enums\ComponentType;use Illuminate\Database\Eloquent\Model;use Sushi\Sushi; class Component extends Model{ use Sushi; protected $casts = [ 'variants' => 'collection', 'requirements' => 'collection', 'type' => ComponentType::class, ]; public function getRows() { return [ [ 'title' => 'Dropdown', 'slug' => 'dropdown', 'description' => 'How to build a dropdown component using Alpine.js.', 'screencast_id' => 111, 'variants' => json_encode([ ['view' => 'patterns.dropdown'], ]), 'type' => ComponentType::COMPONENT->value, 'is_public' => true, 'is_free' => true, 'requirements' => json_encode([ [ 'name' => 'alpinejs', 'version' => 'v3.x', 'url' => 'https://alpinejs.dev/installation', ], ]), ], [ 'title' => 'Modal', 'slug' => 'modal', 'description' => 'How to build a modal component using Alpine.js.', 'screencast_id' => 222, 'variants' => json_encode([ ['view' => 'patterns.modal'], ]), 'type' => ComponentType::COMPONENT->value, 'is_public' => true, 'is_free' => false, 'requirements' => json_encode([ [ 'name' => 'alpinejs', 'version' => 'v3.x', 'url' => 'https://alpinejs.dev/installation', ], [ 'name' => '@alpinejs/focus', 'version' => 'v3.x', 'url' => 'https://alpinejs.dev/plugins/focus', ], ]), ], // ... ]; }}
As you can see in this example, we used the getRows
method instead of setting the $rows
property. This was so we could use the json_encode()
function and utilizes JSON columns for the variants
and requirements
columns on each model. You can also see that Sushi supports casting attributes to different types just as Laravel does.
API data-sources
Another neat use case is getting data from API sources. Raúl, Marcel, Adam, and Caleb mentioned different API sources they've used.
Caleb sends requests to the GitHub Sponsors API to determine who can access the Livewire v2 screencasts, then maps over those results to grab the attributes he needs and formats them in a nice schema for a model. This is a simplified version of the Sponsor
model from the Livewire v2 codebase:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;use Sushi\Sushi; class Sponsor extends Model{ use Sushi; protected $keyType = 'string'; public function user() { return $this->hasOne(User::class, 'github_username', 'username'); } public function getsScreencasts() { // If they sponsor for more than $8, they get access to screencasts. return $this->tier_price_in_cents > 8 * 100; } public function getRows() { return Cache::remember('sponsors', now()->addHour(), function () { return collect($this->fetchSponsors()) ->map(function ($sponsor) { return [ 'id' => $sponsor['sponsorEntity']['id'], 'username' => $sponsor['sponsorEntity']['login'], 'name' => $sponsor['sponsorEntity']['name'], 'email' => $sponsor['sponsorEntity']['email'], // ... ]; }); }); } public function fetchSponsors() { return Http::retry(3, 100) ->withToken( config('services.github.token') )->post('https://api.github.com/graphql', [ 'query' => 'A big ugly GraphQL query' ]); }}
Conclusion
Sushi is a really neat package with some awesome use cases. I'm sure I've barely touched the surface in this article. If you've used the package, let me know how on Twitter!
TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of designtotailwind.com.