Support the ongoing development of Laravel.io ā†’

šŸ£ Sushi ā€” Your Eloquent model driver for other data sources

11 Nov, 2024 4 min read

Photo by JSB Co. on Unsplash

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not every bit of data needs that level of complexity. Sometimes, you have small, static datasetsā€”like a list of countries, settings, or configsā€”that hardly ever change. Setting up a database table for everything can feel like overkill.

Thatā€™s where Sushi comes in. Itā€™s a lightweight package that lets you skip the database entirely for small, static data, even pulling from APIs or config arrays.

What is Laravel Sushi?

image

Sushi allows you to create Eloquent models from data sources other than a database. Instead of setting up a traditional database, you can provide data from an array, config, API, or a CSV file. What I mean is... it can be anything.

It is created by Caleb Porzio (the guy behind Livewire and AlpineJS), Sushi simplifies your data when a full database table is unnecessary.

How to Use Sushi?

The simplest way to use Sushi is by providing data as a hardcoded array. But you can also pull dynamic data from an API or load it from a config array for flexibility. Letā€™s explore three examples:

Installation Let's do the installation first.

composer require calebporzio/sushi

Example 1: Hardcoded Data

Hereā€™s a basic model using a hardcoded array:

<?php

namespace App\Models;

use Sushi\Sushi;

class Country extends Model
{
    // Add the Sushi trait
    use Sushi;

    // Provide data as a hardcoded array
    protected $rows = [
        ['id' => 1, 'abbr' => 'IN', 'label' => 'India'],        
        ['id' => 2, 'abbr' => 'US', 'label' => 'United States'],
    ];
}

Now, you can query it just like a regular database model:

$india = Country::where('abbr', 'IN')->first();

Example 2: Data from a Config Array

You can also load the data from a config file. If you have data in some third-party config or you choose to keep the data outside the model, you can set up eloquent models from that data without going deeper into the code.

Letā€™s say you have a config file like this in config/countries.php:

<?php

return [
    ['id' => 1, 'abbr' => 'IN', 'label' => 'India'],
    ['id' => 2, 'abbr' => 'US', 'label' => 'United States'],
];

Now, you can use Sushi to load this config data into a model:

<?php

namespace App\Models;

use Sushi\Sushi;

class Country extends Model
{
    use Sushi;

    public function getRows()
    {
        // Load the data from the config file
        return config('countries');
    }
}

Example 3: Dynamic Data from an API with Caching

You can also implement Sushi where you pull data from an API. Hereā€™s how you can fetch dynamic data from an API and cache it for an hour:

<?php

namespace App\Models;

use Sushi\Sushi;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class Country extends Model
{
    use Sushi;

    public function getRows()
    {
        // Cache the API data for 1 hour
        return Cache::remember('countries', 60, function () {
            $response = Http::get('https://restcountries.com/v3.1/all');
            $countries = $response->json();

            // Map the API response to the format Sushi expects
            return collect($countries)->map(function ($country) {
                return [
                    'id'    => $country['cca3'],
                    'abbr'  => $country['cca2'],
                    'label' => $country['name']['common'],
                ];
            })->toArray();
        });
    }
}

In this example:

  • Weā€™re fetching data from the REST Countries API.
  • The API response is cached for 1 hour using Laravelā€™s Cache::remember() method.
  • getRows() pulls and transforms the data into the format Sushi requires.

Why Use Sushi?

Sushi is perfect when you need a lightweight solution for static or semi-static datasets, like:

  • Configurations, lists of countries, or languages
  • Predefined roles or permissions
  • Any small dataset that doesnā€™t change often but still needs to be queried

You can skip the database entirely and enjoy the full power of Eloquent without the overhead of migrations and database setup.

One more cool thing: You donā€™t even need an id column unless you want to. Sushi can auto-generate IDs for each row. But keep in mind, if the data changes and the cache is reset, these IDs might change too. So, for stability, itā€™s best to define your own id column for each item.

Note: Since Sushi uses SQLite to store the data, make sure the SQLite extension is enabled in your PHP configuration.

Conclusion

Sushi lets you skip the database setup for smaller datasets and helps you define that data directly in the model, saving time and keeping things lightweight. It is a great tool when dealing with static data, configurations, or even dynamic data from APIs.

Just a side note, our core product CRUD is also compatible with Sushi and you can use it to create a Table for the entries. Our Backpack DevTools also uses Sushi, which shows how practical this tool is. Give it a try - save time and keep things light.šŸ§‘ā€šŸ’»šŸ˜Ž

Last updated 1 day ago.

driesvints liked this article

1
Like this article? Let the author know and give them a clap!

Other articles you might like

April 24th 2024

Find Open-Source Laravel/PHP Projects to Contribute to

Introduction I love open-source software. I love the idea of being able to contribute to a project t...

Read article
November 4th 2024

Laravel Under The Hood - A Little Bit of Macros

Hello šŸ‘‹ How often have you wished for a method that doesn't exist on collections or string helpers?...

Read article
October 30th 2024

Create a backup of your Laravel project on Dropbox

How to quickly create a backup of a Laravel project and store it on Dropbox using Spatie Laravel-bac...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.