By @boris · 2021-09-29 10:12
I've hacked around and built an experimental package.
Laravel Fluent provides a natural PHP way to define your Models' attributes. It automatically builds casts at the runtime and adds a native autocompletion to the models' properties.
With laravel-fluent
, you can define Model attributes as you would do with any other class. The values will be transformed to the corresponding types depending on the native types of the properties.
Before:
<?php
/**
* @property Collection $features
* @property float $price
* @property int $available
*/
class Product extends Model
{
protected $casts = [
'features' => 'collection',
'price' => 'float',
'available' => 'integer',
];
}
After:
<?php
class Product extends Model
{
use Fluent;
public Collection $features;
public float $price;
public int $available;
}
Laravel Fluent supports all native types and Laravel primitive casts. It can be also extended with your custom casters.
<?php
class Order extends Model
{
use Fluent;
public int $amount;
public Carbon $expires_at;
#[AsDecimal(2)]
public float $total;
#[Cast('encrypted:array')]
public array $payload;
}
The package also handles relationships. Relations methods declaration is still required for proper autocompletion. However, the package can automatically resolve relations from attributes.
<?php
class Product extends Model
{
use Fluent;
#[HasMany(Feature::class)]
public Collection $features;
#[BelongsTo]
public Category $category;
// optional, could be resolved automatically
public function features(): HasMany
{
return $this->hasMany(Feature::class);
}
// optional, could be resolved automatically
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
By @samuel · 2021-09-30 18:58
Taylor has forked the package, which could mean that might be added to Laravel 9 core 🤔