Multi-purpose Value Objects for Laravel

  • Reading time ~ 3 min
  • 08.11.2022
Laravel Value Objects is a collection of general-purpose value objects you can use in your Laravel application.

Laravel Value Objects is a collection of general-purpose value objects you can use in your Laravel application. Value objects help represent simple entities such as money or X/Y coordinates on a 2D axis. Specifically, this package offers the following value objects you'd typically run into:

  • Boolean
  • Number
  • Text
  • Email
  • Full Name
  • Name
  • Tax Number
  • UUID

Take working with a user's full name, for example you might need to split up a name string into a first and last name:

$name = new FullName(' Joe User ');
 
$name->fullName(); // 'Joe User'
$name->firstName(); // 'Joe'
$name->lastName(); // 'User'

This package also provides some Laravel-specific goodies, such as extending value objects via Laravel's Macroable trait and Laravel's Conditionable trait, which applies a callback when a condition is "truthy":

TaxNumber::from('PL0123456789')
    ->when(function ($number) {
        return $number->prefix() !== null;
    })
    ->prefix();

Another example is the Number value object, which you can use to scale numbers for example:

$number = new Number('10.20999', scale: 2);
$number = Number::make('10.20999', scale: 2);
$number = Number::from('10.20999', scale: 2);
 
$number->value();   // '10.20'
(string) $number;   // '10.20'
$number->toArray(); // ['10.20']

As you can also see, this package provides a few static constructors you can use to create a value object and handle invalid data via the makeOrNull() static constructor.

You can learn more about this package, get full installation instructions, and view the source code on GitHub. The readme has documentation on how to use each of the provided value objects.

Original
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

I'm full stack laravel developer

I knew my call in programming back in 2006.

WORK EXPERIENCE
CONTACT
Ukraine, Lutsk
+380979856297