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 roasted.dev.

Cube

Laravel Newsletter

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

image
No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project.

Visit No Compromises
Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
DirectoryTree Authorization is a Native Role and Permission Management Package for Laravel image

DirectoryTree Authorization is a Native Role and Permission Management Package for Laravel

Read article
Sort Elements with the Alpine.js Sort Plugin image

Sort Elements with the Alpine.js Sort Plugin

Read article
Anonymous Event Broadcasting in Laravel 11.5 image

Anonymous Event Broadcasting in Laravel 11.5

Read article
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article