Use an API endpoint for an Eloquent model instead of a database table

    And show them in Laravel Nova!

    07 Feb 2020 • Last updated a few seconds ago

    The following tweet caught my attention on the Laravel Discord server.

    This actually works!

    By using calebporzio/sushi and kitetail/zttp you can create Eloquent models using an API endpoint instead of a database table.

    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Sushi\Sushi;
    use Zttp\Zttp;
    
    class GithubUser extends Model
    {
        use Sushi;
    
        public function getRows()
        {
            return Zttp::withHeaders(['User-agent' => 'PHP'])
                ->get('https://api.github.com/users')
                ->json();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    This also means you can display them as Nova resources!

    Nova










     



















    namespace App\Nova;
    
    use Illuminate\Http\Request;
    use Laravel\Nova\Fields\ID;
    use Laravel\Nova\Fields\Text;
    
    class GithubUser extends Resource
    {
        
        public static $model = 'App\GithubUser';
    
        public static $title = 'id';
        
        public static $search = [
            'id',
        ];
    
        public function fields(Request $request)
        {
            return [
                ID::make()->sortable(),
    
                Text::make('avatar_url')
            ];
        }
    
        // ...
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28