Derrick Miller
Derrick Miller

Reputation: 1951

How to implement a Laravel model that loads a resource

I have a Laravel model that loads a resource from a remote SSH server, then stores the returned data in properties within the model. Here is a simplified version of my code:

SomeController.php (Controller)

  $foo = new Foo();
  $foo->load(52); // Load resource #52
  echo 'The title of resource #52 is ' . $foo->getTitle();

Foo.php (Model)

  class Foo extends Model
  {
    private $_id;
    private $_title;
    private $_body;

    public function loadResource($id)
    {
      // ...connect to external SSH server and retrieve resource 
      $this->_id = $resource->id;
      $this->_title = $resource->title;
      $this->_body = $resource->body;
    }

    public function getTitle()
    {
      return $this->_title;
    }

    public function getBody()
    {
      return $this->_body;
    }

  }

Upvotes: 1

Views: 428

Answers (1)

Kevin Bui
Kevin Bui

Reputation: 3045

You might use the "retrieved" model event to achieve that:

https://laravel.com/docs/5.8/eloquent#events

class Foo extends Model
  {

    public static function boot()
    {
        static::retrieved(function (Foo $foo) {
            $foo->resource = getResource();
        )
    }
  }

That's gonna bind the external resource to the resource property when the model is retrieved from the database:

$foo = Foo::find(100);

Then you are able to get resource attributes via the resource property from the model.

$foo->resource->id;
$foo->resource->title;
$foo->resource->body;

Upvotes: 1

Related Questions