Define Model Attributes With Laravel Fluent

Packages

September 7th, 2021

laravel-fluent-featured.png

Laravel Fluent is a package by Boris Lepikhin that provides an expressive way to define model attributes. This package automatically builds casts at runtime and gives you native auto-completion of model properties:

1// Before
2 
3/**
4 * @property Collection $features
5 * @property float $price
6 * @property int $available
7 */
8class Product extends Model
9{
10 protected $casts = [
11 'features' => 'collection',
12 'price' => 'float',
13 'available' => 'integer',
14 ];
15}
16 
17// After
18use Based\Fluent\Fluent;
19 
20class Product extends Model
21{
22 use Fluent;
23 
24 public Collection $features;
25 public float $price;
26 public int $available;
27}

This package supports all native PHP types and laravel primitive casts:

1class Order extends Model
2{
3 use Fluent;
4 
5 public int $amount;
6 public Carbon $expires_at;
7 
8 #[AsDecimal(2)]
9 public float $total;
10 
11 #[Cast('encrypted:array')]
12 public array $payload;
13}

This package can also handle model relations. You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.