wearepixel/laravel-model-objects

A package to easily serialize a Laravel model to be stored in a database for disconnected model access.

1.0.0 2024-05-13 07:21 UTC

This package is not auto-updated.

Last update: 2024-05-28 06:03:37 UTC


README

Latest Version on Packagist Total Downloads GitHub Actions

A package to easily retrieve model objects for easy storage in Laravel

Key Features

  • Retrieve an object from a model
  • Hide fields from the object by using the $hiddenProperties array property
  • Hide relationships from the object by setting a config value

Installation

You can install the package via composer:

composer require wearepixel/laravel-model-objects

Usage

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use WeArePixel\LaravelModelObjects\HasModelObject;

class User extends Model
{
    use HasModelObject;

    protected $hiddenProperties = [
        'user_id',
    ];
}

// ...
$user = User::find(1);
$userObject = $user->modelObject;

Configuration

Publshing The Configuration

The configuration file looks like this:

return [
    /**
     * Hide the primary key from the model object
     */
    'hide_primary_key' => env('LARAVEL_MODEL_OBJECTS_HIDE_PRIMARY_KEY', true),

    /**
     * Hide timestamps from the model object
     */
    'hide_timestamps' => env('LARAVEL_MODEL_OBJECTS_HIDE_TIMESTAMPS', true),
];

If you need to make any changes to the configuration, feel free to publish the configuration file.

php artisan vendor:publish --provider="WeArePixel\LaravelModelObjects\LaravelModelObjectsServiceProvider"

Hiding Model Attributes

This package will automatically hide any additional fields, you add into $hiddenProperties array property.

protected $hiddenProperties = [
    'user_id',
];

This is useful for scenarios where you don't need to store all fields in the object, or you want to hide sensitive information.

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.