szainmehdi
5 years ago

Question: Using Value Objects with Eloquent in Laravel 5

Posted 5 years ago by szainmehdi

Hi all,

I know Laravel 5 has introduced attribute casting in Eloquent, allowing the user to specify scalar types for attributes. However, I'm wondering if anyone has found a way to take this one step further with Value Objects.

// app/User.php
<?php namespace App;

class User extends BaseModel {
    
    protected $casts = [
        'phone' => \App\Support\Phone::class 
    ];

}
<?php namespace App\Support;
// app/Support/Phone.php
class Phone {

    public $number;

    public function __construct($number) {
        $this->number = $number;
    }

    public function getAreaCode() {
        return ''; // TODO
    }
}

If anyone has any suggestions, I'd love to hear.

Thanks!

Please sign in or create an account to participate in this conversation.