Learn Laravel Sushi - The array driver for Eloquent
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:
1<?php 2 3namespace App\Models; 4 5use Sushi\Sushi; 6 7class Role extends Model 8{ 9 // Add the trait10 use Sushi;11 12 // Provide the data as a hardcoded array13 protected $rows = [14 ['id' => 1, 'label' => 'admin'],15 ['id' => 2, 'label' => 'manager'],16 ['id' => 3, 'label' => 'user'],17 ];18}
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.
1<?php 2 3namespace App\Models; 4 5use Sushi\Sushi; 6 7class Role extends Model 8{ 9 use Sushi;10 11 protected $rows = [12 [13 'id' => 1,14 'name' => 'Alabama',15 'abbreviation' => 'AL',16 ],17 [18 'id' => 2,19 'name' => 'Alaska',20 'abbreviation' => 'AK',21 ],22 [23 'id' => 3,24 'name' => 'Arizona',25 'abbreviation' => 'AZ',26 ],27 [28 'id' => 4,29 'name' => 'Arkansas',30 'abbreviation' => 'AR',31 ],32 [33 'id' => 5,34 'name' => 'California',35 'abbreviation' => 'CA',36 ],37 // ...38 ];39}
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:
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6use Sushi\Sushi; 7 8class Series extends Model 9{10 use Sushi;11 12 public function screencasts()13 {14 return $this->hasMany(Screencast::class);15 }16 17 public function getRows()18 {19 return [20 ['id' => 1, 'order' => 1, 'title' => 'Getting Started'],21 ['id' => 2, 'order' => 2, 'title' => 'A Basic Form With Validation'],22 //...23 ];24 }25}
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6use Sushi\Sushi; 7 8class Screencast extends Model 9{10 use Sushi;11 12 public function series()13 {14 return $this->belongsTo(Series::class);15 }16 17 public function getNextAttribute()18 {19 return static::find($this->id + 1);20 }21 22 public function getPrevAttribute()23 {24 return static::find($this->id - 1);25 }26 27 public function getDurationInSecondsAttribute()28 {29 // ...30 }31 32 protected $rows = [33 [34 'title' => 'Installation',35 'slug' => 'installation',36 '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!",37 'video_url' => 'https://vimeo.com/...',38 'code_url' => 'https://github.com/...',39 'duration_in_minutes' => '2:32',40 'series_id' => 1,41 ],42 [43 'title' => 'Data Binding',44 'slug' => 'data-binding',45 '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.",46 'video_url' => 'https://vimeo.com/...',,47 'code_url' => 'https://github.com/...',48 'duration_in_minutes' => '9:11',49 'series_id' => 1,50 ],51 // ...52 ];53}
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:
1$series = Series::with(['screencasts'])->orderBy('order')->get();
Then, you can loop over them in your Blade:
1<div> 2 @foreach($series as $s) 3 <div> 4 <h2>{{ $series->title }}</h2> 5 <div> 6 @foreach($series->screencasts as $screencast) 7 <div> 8 <h3>{{ $screencast->title }}</h3> 9 <p>{{ $screencast->description }}</p>10 </div>11 @endforeach12 </div>13 </div>14 @endforeach15</div>
You can even use Laravel's route model binding to automatically query Sushi models:
1Route::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.
1<?php 2 3namespace App\Models; 4 5use App\Enums\ComponentType; 6use Illuminate\Database\Eloquent\Model; 7use Sushi\Sushi; 8 9class Component extends Model10{11 use Sushi;12 13 protected $casts = [14 'variants' => 'collection',15 'requirements' => 'collection',16 'type' => ComponentType::class,17 ];18 19 public function getRows()20 {21 return [22 [23 'title' => 'Dropdown',24 'slug' => 'dropdown',25 'description' => 'How to build a dropdown component using Alpine.js.',26 'screencast_id' => 111,27 'variants' => json_encode([28 ['view' => 'patterns.dropdown'],29 ]),30 'type' => ComponentType::COMPONENT->value,31 'is_public' => true,32 'is_free' => true,33 'requirements' => json_encode([34 [35 'name' => 'alpinejs',36 'version' => 'v3.x',37 'url' => 'https://alpinejs.dev/installation',38 ],39 40 ]),41 ],42 [43 'title' => 'Modal',44 'slug' => 'modal',45 'description' => 'How to build a modal component using Alpine.js.',46 'screencast_id' => 222,47 'variants' => json_encode([48 ['view' => 'patterns.modal'],49 ]),50 'type' => ComponentType::COMPONENT->value,51 'is_public' => true,52 'is_free' => false,53 'requirements' => json_encode([54 [55 'name' => 'alpinejs',56 'version' => 'v3.x',57 'url' => 'https://alpinejs.dev/installation',58 ],59 [60 'name' => '@alpinejs/focus',61 'version' => 'v3.x',62 'url' => 'https://alpinejs.dev/plugins/focus',63 ],64 ]),65 ],66 // ...67 ];68 }69}
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:
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6use Illuminate\Support\Facades\Cache; 7use Illuminate\Support\Facades\Http; 8use Illuminate\Support\Str; 9use Sushi\Sushi;10 11class Sponsor extends Model12{13 use Sushi;14 15 protected $keyType = 'string';16 17 public function user()18 {19 return $this->hasOne(User::class, 'github_username', 'username');20 }21 22 public function getsScreencasts()23 {24 // If they sponsor for more than $8, they get access to screencasts.25 return $this->tier_price_in_cents > 8 * 100;26 }27 28 public function getRows()29 {30 return Cache::remember('sponsors', now()->addHour(), function () {31 return collect($this->fetchSponsors())32 ->map(function ($sponsor) {33 return [34 'id' => $sponsor['sponsorEntity']['id'],35 'username' => $sponsor['sponsorEntity']['login'],36 'name' => $sponsor['sponsorEntity']['name'],37 'email' => $sponsor['sponsorEntity']['email'],38 // ...39 ];40 });41 });42 }43 44 public function fetchSponsors()45 {46 return Http::retry(3, 100)47 ->withToken(48 config('services.github.token')49 )->post('https://api.github.com/graphql', [50 'query' => 'A big ugly GraphQL query'51 ]);52 }53}
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!