Basics
Eloquentity is a library that allows mapping between Eloquent models and entity classes in Laravel applications.
Creating Eloquentity
$eloquentity = Eloquentity::create();scoped. This will prevent data leakage and ensure that the model instance remains isolated and specific to the current request or job execution.Mapping
To map an Eloquent model to an entity class, you need to define the entity class with properties that correspond to the columns in the database table.
class Post extends Model
{
// ...
}Assuming the Post table has id, title, and content columns, the corresponding entity class would look like this:
class PostEntity
{
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly string $content
) {}
}You can then map an instance of the Post model to a PostEntity using the map method provided by Eloquentity:
$postEntity = $eloquentity->map(Post::findOrFail(1), PostEntity::class);Nullable Columns
If one of the columns in the database table is nullable, you can define the corresponding property in the entity class with a nullable type:
class PostEntity
{
public function __construct(
public readonly int $id,
public readonly ?string $title,
public readonly string $content
) {}
}Persisting
You can create a new instance of an entity class and persist it as an Eloquent model using the persist method:
$postEntity = new PostEntity(123, "My post", "My post content");
$eloquentity->persist($postEntity, Post::class);persist does not save the changes to the database immediately. You need to call the flush method to flush all changes to the database.Flushing Changes
To flush all changes made to entities (including mapped models) to the database, you need to call the flush method:
$eloquentity->flush();This will save all pending changes to the database.