Laravel Model-Property Mapper
This package provides functionality to map your model attributes to local class properties with the same names.
The package requires PHP ^8.x
and Laravel ^8.67
.
Installation
Install the package using composer:
composer require michael-rubel/laravel-model-mapper
Usage
use WithModelMapping;
Then in constructor or any other method:
$this->mapModelAttributes($model);
This is especially handy with Livewire components when you want to map your model data to the view.
For example:
class CompanyProfile extends Component
{
use WithModelMapping;
/**
* Frontend properties.
*
* @var string|null
*/
public ?string $name = null;
public ?string $tax_number = null;
public ?string $address = null;
/**
* @param \App\Models\Company $company
*
* @return void
*/
public function mount(Company $company): void
{
$this->mapModelAttributes($company);
}
}
Why?
Why should I use it like this instead of just passing the model to the view? It's because the models are huge objects and you probably shouldn't expose them to the frontend for security and performance reasons. Another thing is primitive view variables are highly customizable through view composers, while it's harder to decorate in the case of using models.
Logging
As the package doesn't throw an error in case of failed assignment (for example type incompatibility), you may wish to log such an event. The package has failed assignment logging disabled by default, but you can turn it on by publishing the config:
php artisan vendor:publish --tag="model-mapper-config"
Testing
composer test