Skip to content
Advertisement

Laravel – How to pass model to the view without querying database when working with remote API to get Data?

I’m working on a Laravel web project that is fully integrated with external/remote Rest API. I’m trying to pass a model object that returned from API to a GET route by implicitly route binding but the default behavior that Laravel did is trying to reference this model object from the database while no database connection defined in my application.

Advertisement

Answer

You can customize the resolution logic:

class ApiModel
{
    /**
    * Retrieve the model for a bound value.
    *
    * @param  mixed  $value
    * @param  string|null  $field
    * @return IlluminateDatabaseEloquentModel|null
    */
    public function resolveRouteBinding($value, $field = null)
    {
        return Http::get('api/path/for/model')->json();
    }
}

If you need to further modify the model class to have an eloquent-like model, you can use or borrow from jenssegers/model.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement