PHPackages                             isakzhanov-r/laravel-value-object - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. isakzhanov-r/laravel-value-object

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

isakzhanov-r/laravel-value-object
=================================

Value Object for Eloquent

v1.0.0(4y ago)12.5k1MITPHPPHP ^7.4|^8.0

Since Sep 2Pushed 4y ago1 watchersCompare

[ Source](https://github.com/isakzhanov-r/laravel-value-object)[ Packagist](https://packagist.org/packages/isakzhanov-r/laravel-value-object)[ RSS](/packages/isakzhanov-r-laravel-value-object/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (2)Used By (1)

Laravel Value Object
====================

[](#laravel-value-object)

> Allows you to create value objects in eloquent models, in the form of casts that are then stored in the database, or to represent the data as an object.

 [![Total Downloads](https://camo.githubusercontent.com/aa0570bc22c19d6907427b0fee076dbde799b5743cdfa51831526ad3111d2a7d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6973616b7a68616e6f762d722f6c61726176656c2d76616c75652d6f626a6563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/isakzhanov-r/laravel-value-object) [![Latest Stable Version](https://camo.githubusercontent.com/cf78b066cb67db842b4a5341a4741bda29a3ec8234363c49504c64e9a5193e42/68747470733a2f2f706f7365722e707567782e6f72672f6973616b7a68616e6f762d722f6c61726176656c2d76616c75652d6f626a6563742f762f737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/isakzhanov-r/laravel-value-object) [![Latest Unstable Version](https://camo.githubusercontent.com/4280a669b03dd423aed4b7a2aa4455ac2f7f1f7ee6325998ce66e3dfc7d847b5/68747470733a2f2f706f7365722e707567782e6f72672f6973616b7a68616e6f762d722f6c61726176656c2d76616c75652d6f626a6563742f762f756e737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/isakzhanov-r/laravel-value-object) [![License](https://camo.githubusercontent.com/b07c74080a46efbd3cbeab27c1d8f6fddbc8172cc2a393b7e574083d5999e941/68747470733a2f2f706f7365722e707567782e6f72672f6973616b7a68616e6f762d722f6c61726176656c2d76616c75652d6f626a6563742f6c6963656e73653f666f726d61743d666c61742d737175617265)](LICENSE)

Contents
--------

[](#contents)

- [Installation](#installation)
- [Usage](#usage)
    - [Creating](#creating)
    - [Validation](#validation)
    - [Use in Model](#use-in-model)
    - [Transform data](#transform)
    - [Serialize and unserialize](#serialize-and-unserialize)
- [License](#license)

Installation
------------

[](#installation)

To get the latest version of Laravel Value Object package, simply require the project using [Composer](https://getcomposer.org):

```
$ composer require isakzhanov-r/laravel-value-object
```

Instead, you can, of course, manually update the dependency block `require` in `composer.json` and run `composer update` if you want to:

```
{
    "require-dev": {
        "isakzhanov-r/laravel-value-object": "^1.0"
    }
}
```

Usage
-----

[](#usage)

### Creating

[](#creating)

To use `Value Object`, you need to create a class that will inherit from the abstract ValueObject class

```
use IsakzhanovR\ValueObject\ValueObject;

class Temperature extends ValueObject
{
    ....
}
```

The ValueObject class has mandatory methods for implementation, `transform` and `rules`

```
use IsakzhanovR\ValueObject\ValueObject;

class Temperature extends ValueObject
{
    protected function transformInput($value)
    {
        return $value;
    }

    protected function rules(): array
    {
        return [];
    }
}
```

The ValueObject inheritor class has two methods for creating an object, via `new FooValueObject($value, $key)` and via a static call to the `create` function

```
  $temperature = new Temperature(25);

  $temperature = Temperature::create(25);
```

if the key is not passed to the function argument, it is generated automatically from the class name

```
 {
  #key: "temperature"
  -value: 25
 }

 echo $temperature;  // 25
```

### Validation

[](#validation)

The data in ValueObject must be valid for this, the `Illuminate\Validation\ValidatesWhenResolvedTrait` validation trait is used. The same trait is used in `FormRequest`. To define rules for the validator, use the `rules` method

```
use IsakzhanovR\ValueObject\ValueObject;

class Temperature extends ValueObject
{
    ....

    protected function rules(): array
    {
        return [
            $this->key => ['required','numeric','between:-100,100']
        ];
    }
}
```

If ValueObject is array, then its value is validated in the same way:

```
use IsakzhanovR\ValueObject\ValueObject;

class Address extends ValueObject
{
    ....

    protected function rules(): array
    {
        return [
            $this->key              => ['required', 'array'],
            $this->key . '.country' => ['required', 'string'],
            $this->key . '.city'    => ['required', 'string'],
            $this->key . '.street'  => ['required', 'string'],
            $this->key . '.number'  => ['required', 'numeric'],
        ];
    }
}
```

For custom error messages, use the `messages` method:

```
use IsakzhanovR\ValueObject\ValueObject;

class Temperature extends ValueObject
{
    ....

    protected function messages(): array
    {
        return [
            $this->key.'.between' => 'The range of tmp temperatures should be from -100 to +100',
        ];
    }
}
```

You can also declare an `authorize` method that returns `true` or `false`.

### Use in Model

[](#use-in-model)

To use `ValueObject` in Eloquent models, you do not need to add anything, just specify it in `$casts`.

Let's say you have an Eloquent `Whether` model . You may want to apply transformations to this field or get a value in degrees Celsius, Fahrenheit or Kelvin. If you use this type of field in multiple models, copying and pasting getAttribute functions can be difficult.

Such valuable items become very useful. Let's see how to do this. First, we created a weather model that will have a temperature field brought to the temperature value object.

```
use Illuminate\Database\Eloquent\Model;

class Weather extends Model
{
    ....

    protected $casts = [
        ...
        'temperature' => Temperature::class,
        ...
      ];

    ....
}
```

We will add the following methods to the temperature object

```
use IsakzhanovR\ValueObject\ValueObject;

class Temperature extends ValueObject
{
    ....

    public function inCelsius()
    {
        return (float) $this->value();
    }

    public function inKelvin()
    {
        return (float) $this->value() + 273.15;
    }

    public function inFahrenheit()
    {
        return (float) $this->value() * 1.8 + 32;
    }
}
```

Objects with a value are stored in the database as a prime number and can be used as follows:

```
    $weather = new Weather;
    $weather->temperature = new Temperature(9);

    echo $weather->temperature;                 // Prints '9'
    echo $weather->temperature->value();        // Prints '9'
    echo $weather->temperature->inKelvin();     // Prints 282.15
    echo $weather->temperature->inFahrenheit(); // Prints 48.2
```

To write to the model, you must use an instance of ValueObject:

```
    $weather = new Weather;
    $weather->temperature = new Temperature(9);
    $weather->save()

//Or

    $temperature = new Temperature(9);
    $weather = Weather::create(compact('temperature'));

//Or
    $weather = Weather::create(Temperature::create(9)->toDTO());
```

You may also use Accessors and Mutators, just like in Eloquent Models.

```
class Weather extends Model
{
    ....

    protected $casts = [
        ...
        'temperature' => Temperature::class,
        ...
      ];

    protected $appends = ['celsius','kelvin','fahrenheit']

    public function getCelsiusAttribute()
    {
        return $this->temperature->inCelsius();
    }

    public function getKelvinAttribute()
    {
        return $this->temperature->inKelvin();
    }

    public function getFahrenheitAttribute()
    {
        return $this->temperature->inFahrenheit();
    }
}
```

### Transform data

[](#transform-data)

Data transformation is intended for minor manipulations with data, for example, clearing unnecessary characters. This method is performed before validation. The `transformInput` function is also executed in the Eloquent model with both `get` and `set` methods

```
use IsakzhanovR\ValueObject\ValueObject;

class Title extends ValueObject
{
    protected function transformInput($value)
    {
        $value = trim(e($value));

        return mb_ucfirst(Str::lower($value));
    }

    ...
}
```

### Serialize and unserialize

[](#serialize-and-unserialize)

Sometimes objects with a value may not be so simple and may require several fields instead of one. Let's say we have a `User` model with an address field that contains the country, city, street and house number, this field in the database is of the `json` type. Then we could define the `User` model as we did before:

```
class User extends Model
{
    protected $casts = [
        'address' => Address::class
    ];
}
```

Then we will be able to define the address value object as follows:

```
use IsakzhanovR\ValueObject\ValueObject;

class Address extends ValueObject
{
    protected function transformInput($value)
    {
        return $value;
    }

    protected function rules(): array
    {
        return [
            $this->key              => ['required', 'array'],
            $this->key . '.country' => ['required', 'string'],
            $this->key . '.city'    => ['required', 'string'],
            $this->key . '.street'  => ['required', 'string'],
            $this->key . '.number'  => ['required', 'numeric'],
        ];
    }
}
```

In order to write data, you need to convert an array to a json string and, accordingly, when reading this string from the database, you need to convert it back to an array, for this we will need the `serialize` and `unserialize` static methods. These methods are executed only if they are declared.

```
class Address Extends ValueObject
{
    ....

    public static function unserialize($value)
    {
        return json_decode($value, true);
    }

    public static function serialize($value)
    {
        return json_encode($value);
    }

    ....
}
```

License
-------

[](#license)

This package is released under the[MIT License](LICENSE.md).

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1714d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a3fd6aab3f44bd9e13bdcb29861643956862d786211d8ed2d5630217569fc232?d=identicon)[isakzhanovR](/maintainers/isakzhanovR)

---

Top Contributors

[![isakzhanov-r](https://avatars.githubusercontent.com/u/38492287?v=4)](https://github.com/isakzhanov-r "isakzhanov-r (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/isakzhanov-r-laravel-value-object/health.svg)

```
[![Health](https://phpackages.com/badges/isakzhanov-r-laravel-value-object/health.svg)](https://phpackages.com/packages/isakzhanov-r-laravel-value-object)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[orchestra/canvas

Code Generators for Laravel Applications and Packages

21017.2M158](/packages/orchestra-canvas)[kirschbaum-development/commentions

A package to allow you to create comments, tag users and more

12369.2k](/packages/kirschbaum-development-commentions)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[glhd/special

1929.4k](/packages/glhd-special)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
