Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a fetched result fit into a model?

Let’s say I do a

$response = Http::get('http://example.com');
$i_want_to_be_a_model = $response->json();

And I have a \App\Models\Example model.

How can I make the $i_want_to_be_a_model to be an Example model?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to do this, because I want to add a method statusText() to the model, that is not part of the result.

class Example extends Model {
   
  // ..
  public string $statusText;
  public int $status;


  public function statusText() {
    switch ($this->status) {
      case 100:
        $this->statusText = "foo";
        break;
      //..
      default:
        $this->statusText = "bar";
    }
  }
}

If there is a more elegant way if doing this, please let me know.

>Solution :

You can define a helper function or a Factory class to create objects of Example class.

For eg:

<?php

namespace App\Factories;

use App\Models\Example;
use Illuminate\Support\Facades\Schema;

class ExampleFactory
{

    public function __construct(array $attributes)
    {
        $example = new Example;

        $fields = Schema::getColumnListing($example->getTable());

        foreach($attributes as $field => $value) {
            if(in_array($field, $fields) {
                $example->{$field} = $value;
            }
        }

        return $example;
    }

    public static function makeFromArray(array $attributes)
    {
        return new static(... $attributes);
    }
}

Then you can use the Factory as

// use App\Factories\ExampleFactory;

$response = Http::get('http://example.com');

$example = ExampleFactory::makeFromArray(json_decode($response->json(), true));

//Now you can do whatever you want with the instance, even persist in database
$example->save();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading