Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
IsraelOrtuno committed Jun 1, 2023
1 parent 734fb90 commit f427095
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions README.md
Expand Up @@ -29,6 +29,12 @@ composer require devio/laravel-model-cast

## Usage

You need at least 2 classes for this to work, a *generic* class which will be the base Model class with all common attributes and the specific casted class which will be resolved using those attributes.

Let's use cars in our example. `Car` will be our generic model and `TeslaCar` and `FordCar` the more specific classes the cars will be resolved to.

The base model should just use the `CastsModel` trait and implement the `getCastedModelClass` method which will be responsible of resolving which class should be this model be casted to based on its attributes data.

```php
class Car extends Model implements Castable
{
Expand All @@ -44,15 +50,29 @@ class Car extends Model implements Castable
}
}

class TeslaCar extends Car {
}
class TeslaCar extends Car {}
class FordCar extends Car {}


```

That's all to do. The underlying logic will be casting our `Car` instances to `TeslaCar` or `FordCar` when retrieving models:

```php
$instance = Car::find(1);
$instance::class; // -> TeslaCar
```

$instance = Car::create(['brand' => 'tesla', ...]);
It will also work right when creating a model using the `create` method:

```php
$instance = Car::create(['brand' => 'tesla']);
$instance::class; // -> TeslaCar
```

Eloquent collections will be casted too:

```php
$collection = Car::all();
$collection[0]::class; // -> TeslaCar
$collection[1]::class; // -> FordCar
Expand Down

0 comments on commit f427095

Please sign in to comment.