Get expert guidance in a few days with a Laravel code review

Learn Laravel Sushi - The array driver for Eloquent

Published on by

Learn Laravel Sushi - The array driver for Eloquent image

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!

Jason Beggs photo

TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of designtotailwind.com.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article