Boost your Eloquent Models with Laravel Lift

Published on by

Boost your Eloquent Models with Laravel Lift image

Lift is a package that boosts your Eloquent Models in Laravel.

It lets you create public properties in Eloquent Models that match your table schema. This makes your models easier to read and work with in any IDE.

It provides a simple way to set up your models, focusing on simplicity and ease of use by using PHP 8’s attributes.

The package depends on Eloquent Events to work. This means the package fits easily into your project without needing any major changes (unless you’ve turned off event triggering).

In this post, let's take a deep dive into Lift and learn about all the features that it provides.

Installing Laravel Lift

You can install the package via composer:

composer require wendelladriel/laravel-lift

To start using Lift, you need to add the Lift trait to your Eloquent Models, and you're ready to go.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
}

Features

Out-of-the-box, when you add the Lift trait to your Eloquent Models, you can create public properties on them, making them easier to understand and to work within any IDE.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
public $id;
 
public $name;
 
public $price;
}

The magic happens when you start using the Attributes that the package provides.

Class Attributes

DB Attribute

Lift provides a DB attribute that you can use to define the connection, table, and timestamps of your model.

Without Lift

use Illuminate\Database\Eloquent\Model;
 
final class Product extends Model
{
public $timestamps = false;
 
protected $connection = 'mysql';
 
protected $table = 'custom_products_table';
 
// ...
}

With Lift

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\DB;
use WendellAdriel\Lift\Lift;
 
#[DB(connection: 'mysql', table: 'custom_products_table', timestamps: false)]
final class Product extends Model
{
use Lift;
// ...
}

Relationships Attributes

Lift provides attributes to define relationships between models, so instead of defining them using methods, you can define them as attributes instead. All the relationships attributes accept the same parameters that the methods accept.

Without Lift

// Post.php
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
 
final class Post extends Model
{
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
// ...
}
 
// Comment.php
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
final class Comment extends Model
{
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
// ...
}

With Lift

// Post.php
 
use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Relations\HasMany;
use WendellAdriel\Lift\Lift;
 
#[HasMany(Comment::class)]
final class Post extends Model
{
use Lift;
// ...
}
 
// Comment.php
 
use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Relations\BelongsTo;
use WendellAdriel\Lift\Lift;
 
#[BelongsTo(Post::class)]
final class Comment extends Model
{
use Lift;
// ...
}

You can check all the available relationships attributes in the docs.

The relationships will work the same way as if you had defined them using methods.

Property Attributes

Cast Attribute

Lift provides a Cast attribute that you can use to define the cast of your model properties. Besides casting the values, it also allows you to type your properties.

Without Lift

use Illuminate\Database\Eloquent\Model;
 
final class Product extends Model
{
protected $casts = [
'id' => 'int',
'name' => 'string',
'price' => 'float',
'active' => 'boolean',
'expires_at' => 'immutable_datetime',
];
}

With Lift

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Cast('string')]
public string $name;
 
#[Cast('float')]
public float $price;
 
#[Cast('boolean')]
public bool $active;
 
#[Cast('immutable_datetime')]
public CarbonImmutable $expires_at;
}

Column Attribute

Lift provides a Column attribute that you can use to customize the column name of your model properties and to define default values to them.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Column;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Cast('string')]
#[Column('product_name')]
public string $name;
 
#[Cast('float')]
#[Column(name: 'product_price', default: 0.0]
public float $price;
}

In the example above, the name property will be mapped to the product_name column, and the price property will be mapped to the product_price column, with a default value of 0.0.

You can even pass a function name to the default value, which will be called when the property is saved to the database.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Column;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Cast('string')]
#[Column('product_name')]
public string $name;
 
#[Cast('float')]
#[Column(name: 'product_price', default: 0.0]
public float $price;
 
#[Cast('float')]
#[Column(default: 'generatePromotionalPrice')]
public float $promotional_price;
 
public function generatePromotionalPrice(): float
{
return $this->price * 0.8;
}
}

Fillable Attribute

When using the Lift trait, all the attributes of your model are set to guarded. You can use the Fillable attribute to define which properties can be mass-assigned.

Without Lift

use Illuminate\Database\Eloquent\Model;
 
final class Product extends Model
{
protected $fillable = [
'name',
'price',
];
 
protected $casts = [
'id' => 'int',
'name' => 'string',
'price' => 'float',
];
}

With Lift

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
public string $name;
 
#[Fillable]
#[Cast('float')]
public float $price;
}

Hidden Attribute

Lift provides a Hidden attribute that you can use to hide properties from the model when it's converted to an array or JSON.

Without Lift

use Illuminate\Database\Eloquent\Model;
 
final class Product extends Model
{
protected $fillable = [
'name',
'price',
'active',
];
 
protected $casts = [
'id' => 'int',
'name' => 'string',
'price' => 'float',
'active' => 'boolean',
];
 
protected $hidden = [
'active',
];
}

With Lift

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Hidden;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
public string $name;
 
#[Fillable]
#[Cast('float')]
public float $price;
 
#[Hidden]
#[Fillable]
#[Cast('boolean')]
public bool $active;
}

Immutable Attribute

Lift provides an Immutable attribute that you can use to make properties immutable. This means that once the model is created, the property can't be changed. If you try to change it, an WendellAdriel\Lift\Exceptions\ImmutablePropertyException will be thrown.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Immutable;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Immutable]
#[Fillable]
#[Cast('string')]
public string $name;
}
 
$product = Product::query()->create([
'name' => 'Product 1',
]);
 
$product->name = 'Product 2';
$product->save(); // Throws an WendellAdriel\Lift\Exceptions\ImmutablePropertyException

PrimaryKey Attribute

Lift provides a PrimaryKey attribute that you can use to customize the primary key of your model.

Without Lift

use Illuminate\Database\Eloquent\Model;
 
final class Product extends Model
{
public $incrementing = false;
 
protected $primaryKey = 'uuid';
 
protected $keyType = 'string';
// ...
}

With Lift

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\PrimaryKey;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[PrimaryKey(type: 'string', incrementing: false)]
#[Cast('string')]
public string $uuid;
// ...
}

Rules Attribute

Lift provides a Rules attribute that you can use to define validation rules for your model properties.

The validations can be set the same way you would do in a Laravel Form Request, and you can even set custom messages for each rule.

⚠️ The rules will be validated only when you save your model (create or update)

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Rules;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
#[Rules(['required', 'string', 'max:255'])]
public string $name;
 
#[Fillable]
#[Cast('float')]
#[Rules(['required', 'numeric', 'min:0.0'])]
public float $price;
 
#[Fillable]
#[Cast('boolean')]
#[Rules(rules: ['required', 'boolean'], messages: ['required' => 'You must set the active status for the product'])]
public bool $active;
}

Watch Attribute

By default, Eloquent already fires events when a model is created, updated, deleted, etc. But that's a generic event, and sometimes, you need to fire a specific event when a property is changed. That's where the Watch attribute comes in.

You can define a custom event that will be fired when a property changes. The event will receive as a parameter the updated model instance.

// Product.php
 
use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Watch;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
public string $name;
 
#[Fillable]
#[Cast('float')]
#[Watch(PriceChangedEvent::class)]
public float $price;
 
#[Fillable]
#[Cast('boolean')]
public bool $active;
}
 
// PriceChangedEvent.php
 
final class PriceChangedEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
 
public function __construct(
public Product $product,
) {
}
}

Methods

Besides all the Attributes the package provides, it also provides some methods you can use to get more information about your models.

customColumns()

It will return an array with all the custom columns you defined in your model.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Column;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Cast('string')]
#[Column('product_name')]
public string $name;
 
#[Cast('float')]
#[Column(name: 'product_price', default: 0.0]
public float $price;
}
 
Product::customColumns();
 
// WILL RETURN
[
'name' => 'product_name',
'price' => 'product_price',
]

defaultValues()

It will return an array with all the properties that have a default value defined. If the default value is a function, the function name will be returned instead of the function result since this is a static call.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Column;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Cast('string')]
#[Column('product_name')]
public string $name;
 
#[Cast('float')]
#[Column(name: 'product_price', default: 0.0]
public float $price;
 
#[Cast('float')]
#[Column(default: 'generatePromotionalPrice')]
public float $promotional_price;
 
public function generatePromotionalPrice(): float
{
return $this->price * 0.8;
}
}
 
Product::defaultValues();
 
// WILL RETURN
[
'price' => 0.0,
'promotional_price' => 'generatePromotionalPrice',
]

immutableProperties()

It will return an array with all the properties that are immutable.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Immutable;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Immutable]
#[Fillable]
#[Cast('string')]
public string $name;
}
 
Product::immutableProperties();
 
// WILL RETURN
[
'name',
]

validationMessages()

It will return an array with all the validation messages you defined in your model.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Rules;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
#[Rules(['required', 'string', 'max:255'])]
public string $name;
 
#[Fillable]
#[Cast('float')]
#[Rules(['required', 'numeric', 'min:0.0'])]
public float $price;
 
#[Fillable]
#[Cast('boolean')]
#[Rules(rules: ['required', 'boolean'], messages: ['required' => 'You must set the active status for the product'])]
public bool $active;
}
 
Product::validationMessages();
 
// WILL RETURN
[
'name' => [],
'price' => [],
'active' => [
'required' => 'You must set the active status for the product',
],
]

validationRules()

It will return an array with all the validation rules you defined in your model.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Rules;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
#[Rules(['required', 'string', 'max:255'])]
public string $name;
 
#[Fillable]
#[Cast('float')]
#[Rules(['required', 'numeric', 'min:0.0'])]
public float $price;
 
#[Fillable]
#[Cast('boolean')]
#[Rules(rules: ['required', 'boolean'], messages: ['required' => 'You must set the active status for the product'])]
public bool $active;
}
 
Product::validationRules();
 
// WILL RETURN
[
'name' => ['required', 'string', 'max:255'],
'price' => ['required', 'numeric', 'min:0.0'],
'active' => ['required', 'boolean'],
]

watchedProperties()

It will return an array with all the properties with a custom event defined.

use Illuminate\Database\Eloquent\Model;
use WendellAdriel\Lift\Attributes\Cast;
use WendellAdriel\Lift\Attributes\Fillable;
use WendellAdriel\Lift\Attributes\Watch;
use WendellAdriel\Lift\Lift;
 
final class Product extends Model
{
use Lift;
 
#[Cast('int')]
public int $id;
 
#[Fillable]
#[Cast('string')]
public string $name;
 
#[Fillable]
#[Cast('float')]
#[Watch(PriceChangedEvent::class)]
public float $price;
 
#[Fillable]
#[Cast('boolean')]
public bool $active;
}
 
Product::watchedProperties();
 
// WILL RETURN
[
'price' => PriceChangedEvent::class,
]

Conclusion

Lift is a package that brings some features of tools like Doctrine, Spring and Entity Framework to Eloquent.

It makes your models easier to read and understand and with a cleaner look by taking advantage of PHP 8's attributes.

Wendell Adriel photo

Software Engineer 💻 Open Source Enthusiast 🔥 Building solutions since 2009 🚀

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article