In a recent article, I showed how to set up an Eloquent model for data sources other than DB. In this article, I'll show how you can li...
In a recent article, I showed how to set up an Eloquent model for data sources other than DB. In this article, I'll show how you can list and preview data coming from other data sources (like an API), using Backpack's CRUD Panels.
Let's take an example. I fetch a list of countries from an API and show the received data using Backpack's List Operation. The steps are very easy and wouldn't take much time:
Step 1:
Install Sushi via the following Composer command.
composer require calebporzio/sushi
Step 2:
Create a Country
model, add the Sushi
trait, and define the getRows()
function to fetch the data from API and return as a collection.
namespace App\Models;
use Sushi\Sushi;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
use Sushi;
use CrudTrait;
protected $keyType = 'string';
// define schema to work even if the dataset is empty
protected $schema = [
'id' => 'string',
'abbr' => 'string',
'label' => 'string',
];
public function getRows()
{
// Cache the API data for 1 hour
return Cache::remember('countries', 3600, 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:
Cache::remember()
method.getRows()
pulls and transforms the data into the format Sushi requires. The end result is an Eloquent model that pulls data from the API, instead of the DB.Step 3: Now, hook this up to a Backpack CRUD. We can treat our Sushi model just like any Laravel model, simply run :
php artisan backpack:crud country
class CountryCrudController extends CrudController
{
...
protected function setupListOperation()
{
CRUD::column('id');
CRUD::column('abbr');
CRUD::column('label');
}
protected function setupShowOperation()
{
$this->setupListOperation();
}
}
and Boom! You will see Backpack's List and Show Operation populating the API data.
Backpack will treat the Country model as pulling data from the database, even though Sushi handles it entirely in memory. You can also check the examples of other data sources in the previous article. I hope this tutorial helps you set up something similar for your project needs. 🍣🍴 Happy Sushing!
Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.
What do you think about this?
Wondering what our community has been up to?