• Reading time ~ 1 min
  • 08.11.2022

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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297