PHPackages                             kodooy/name-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. [Database &amp; ORM](/categories/database)
4. /
5. kodooy/name-value-object

ActiveLibrary[Database &amp; ORM](/categories/database)

kodooy/name-value-object
========================

A Laravel package for handling name value objects and database casting

v1.0.0(7mo ago)01MITPHPPHP ^8.2

Since Oct 2Pushed 7mo agoCompare

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

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

Laravel Name Value Object Package
=================================

[](#laravel-name-value-object-package)

A Laravel package for handling name value objects and database casting.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.0, 11.0, or 12.0

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

[](#installation)

```
composer require kodooy/name-value-object
```

Usage
-----

[](#usage)

### Database Casting

[](#database-casting)

Your database table should have `first_name` and `last_name` columns:

```
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('first_name');
    $table->string('last_name');
    $table->timestamps();
});
```

Add the cast to your Eloquent model:

```
use Kodooy\NameValueObject\Casts\Name;

class User extends Model
{
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
    ];

    protected $casts = [
        'name' => Name::class,
    ];
}
```

Usage:

```
use Kodooy\NameValueObject\ValueObjects\Name;

$user = new User();
$user->name = new Name('John', 'Doe');
$user->save();
```

In controller:

```
use Kodooy\NameValueObject\ValueObjects\Name;

class UsersController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'last_name'  => ['required', 'string', 'max:100'],
            'email'      => ['required', 'email', 'unique:users,email'],
        ]);

        $user = User::create([
            'name' => new Name(
                $validated['first_name'],
                $validated['last_name']
            ),
            'email' => $validated['email'],
        ]);

        // ...
    }
}
```

The name is automatically cast when retrieved:

```
echo $user->name->full();     // 'John Doe'
echo $user->name->first();    // 'John'
echo $user->name->last();     // 'Doe'
echo $user->name->initials(); // 'JD'
echo $user->name;             // 'John Doe'
```

API Reference
-------------

[](#api-reference)

### Name Value Object

[](#name-value-object)

The `Name` value object provides the following methods:

#### Constructor

[](#constructor)

```
new Name(string $firstName, string $lastName)
```

Creates a new Name instance. Both parameters are required and cannot be empty.

- **Parameters:**
    - `$firstName`: The first name (will be trimmed and capitalized)
    - `$lastName`: The last name (will be trimmed and capitalized)
- **Throws:** `InvalidArgumentException` if either name is empty

#### Basic Access Methods

[](#basic-access-methods)

```
$name->first(): string
```

Returns the first name.

```
$name->last(): string
```

Returns the last name.

```
$name->full(): string
```

Returns the full name (first name + space + last name).

#### Formatting Methods

[](#formatting-methods)

```
$name->initials(string $separator = ''): string
```

Returns the initials with optional separator.

- Examples: `initials()` → "JD", `initials('.')` → "J.D.", `initials('-')` → "J-D"

```
$name->monogram(): string
```

Returns the monogram format with periods.

- Example: "J.D."

```
$name->formal(): string
```

Returns the name in formal format (Last, First).

- Example: "Doe, John"

```
$name->casual(): string
```

Returns the casual format (First + Last initial).

- Example: "John D."

```
$name->abbreviated(): string
```

Returns the abbreviated format (First initial + Last name).

- Example: "J. Doe"

```
$name->reverse(): string
```

Returns the reversed format (Last + First).

- Example: "Doe John"

#### Variation Methods

[](#variation-methods)

```
$name->withPrefix(string $prefix): string
```

Returns the name with a prefix.

- Examples: `withPrefix('Dr.')` → "Dr. John Doe", `withPrefix('Mr.')` → "Mr. John Doe"

```
$name->withSuffix(string $suffix): string
```

Returns the name with a suffix.

- Examples: `withSuffix('Jr.')` → "John Doe Jr.", `withSuffix('III')` → "John Doe III"

#### Privacy Methods

[](#privacy-methods)

```
$name->masked(int $visibleChars = 1, string $maskChar = '*'): string
```

Returns a masked version of the name.

- **Parameters:**
    - `$visibleChars`: Number of visible characters from the start (default: 1)
    - `$maskChar`: Character to use for masking (default: '\*')
- Example: `masked()` → "J\*\*\* D\*\*\*", `masked(2, '#')` → "Jo## Do#"

```
$name->obfuscated(): string
```

Returns a SHA256 hash of the full name for privacy.

- Example: "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"

#### Comparison Methods

[](#comparison-methods)

```
$name->equals(Name $other): bool
```

Checks if this name is equal to another Name instance.

- Performs case-sensitive comparison of both first and last names

#### Data Conversion Methods

[](#data-conversion-methods)

```
$name->toArray(): array
```

Returns an array representation containing:

- `first_name`: The first name
- `last_name`: The last name
- `full_name`: The full name
- `initials`: The initials

```
$name->__toString(): string
```

Returns the full name. Allows the object to be used as a string.

- Example: `echo $name; // "John Doe"`

#### Static Factory Methods

[](#static-factory-methods)

```
Name::fromArray(array $data): Name
```

Creates a Name instance from an array.

- **Accepted keys:** `first_name`/`firstname` and `last_name`/`lastname`
- **Throws:** `InvalidArgumentException` if required keys are missing

```
Name::fromFullName(string $fullName): Name
```

Creates a Name instance from a full name string.

- **Parameter:** `$fullName` - Must contain exactly two words separated by space
- **Throws:** `InvalidArgumentException` if format is invalid
- Example: `fromFullName('John Doe')` → Name('John', 'Doe')

```
Name::fromEmail(string $email): Name
```

Creates a Name instance from an email address.

- **Parameter:** `$email` - Must be in format ""
- **Throws:** `InvalidArgumentException` if email format is invalid
- Example: `fromEmail('john.doe@example.com')` → Name('John', 'Doe')

```
Name::random(): Name
```

Generates a random Name instance from predefined lists.

- Returns a Name with randomly selected first and last names

#### Usage Examples

[](#usage-examples)

```
use Kodooy\NameValueObject\ValueObjects\Name;

// Creating a name
$name = new Name('john', 'doe');

// Accessing properties
echo $name->first();    // 'John' (auto-capitalized)
echo $name->last();     // 'Doe' (auto-capitalized)
echo $name->full();     // 'John Doe'
echo $name->initials(); // 'JD'
echo $name;             // 'John Doe' (via __toString)

// Array operations
$array = $name->toArray();
// ['first_name' => 'John', 'last_name' => 'Doe', 'full_name' => 'John Doe', 'initials' => 'JD']

$name2 = Name::fromArray(['first_name' => 'Jane', 'last_name' => 'Smith']);

// Comparison
$areEqual = $name->equals($name2); // false
```

Error Handling
--------------

[](#error-handling)

### Invalid Data Handling

[](#invalid-data-handling)

The Name value object validates input and throws exceptions for invalid data:

```
use Kodooy\NameValueObject\ValueObjects\Name;
use InvalidArgumentException;

// This will throw InvalidArgumentException
try {
    $name = new Name('', 'Doe'); // Empty first name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "First name cannot be empty."
}

try {
    $name = new Name('John', ''); // Empty last name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "Last name cannot be empty."
}

try {
    $name = new Name('   ', 'Doe'); // Whitespace-only first name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "First name cannot be empty."
}
```

### Controller Validation

[](#controller-validation)

Proper validation in your controller prevents exceptions:

```
use Kodooy\NameValueObject\ValueObjects\Name;
use Illuminate\Http\Request;
use InvalidArgumentException;

class UsersController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => ['required', 'string', 'min:1', 'max:100'],
            'last_name'  => ['required', 'string', 'min:1', 'max:100'],
            'email'      => ['required', 'email', 'unique:users,email'],
        ]);

        try {
            $user = User::create([
                'first_name' => $validated['first_name'],
                'last_name'  => $validated['last_name'],
                'email'      => $validated['email'],
            ]);

            // Access the name cast safely
            $fullName = $user->name->full();

        } catch (InvalidArgumentException $e) {
            // Handle unexpected validation bypass
            return response()->json(['error' => 'Invalid name data'], 422);
        }

        return response()->json($user);
    }
}
```

### Cast Error Handling

[](#cast-error-handling)

When using the cast with invalid data types:

```
use Kodooy\NameValueObject\ValueObjects\Name;
use InvalidArgumentException;

$user = new User();

try {
    // This will throw InvalidArgumentException
    $user->name = 'Just a string'; // Must be Name instance
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "Value must be an instance of Name."
}

// Correct usage
$user->name = new Name('John', 'Doe'); // Works correctly
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance63

Regular maintenance activity

Popularity1

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

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

228d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1a1da6abe471f71e299fc5ad78a8603e94afde48c4a84289e524f691b235cc93?d=identicon)[kodooy](/maintainers/kodooy)

---

Tags

laravelValue Objectnamecast

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/kodooy-name-value-object/health.svg)

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

###  Alternatives

[silber/bouncer

Eloquent roles and abilities.

3.6k4.4M25](/packages/silber-bouncer)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)

PHPackages © 2026

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