Home > Enterprise >  How to make a fetched result fit into a model?
How to make a fetched result fit into a model?

Time:06-03

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?

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.

CodePudding user response:

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();
  • Related