All Projects → sebastiaanluca → laravel-boolean-dates

sebastiaanluca / laravel-boolean-dates

Licence: MIT License
Automatically convert Eloquent model boolean attributes to dates (and back).

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to laravel-boolean-dates

laravel-loggable
🎥 📽 🎞 Log your model changes in multiple ways
Stars: ✭ 58 (+87.1%)
Mutual labels:  eloquent, model
Eager Load Pivot Relations
Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Stars: ✭ 134 (+332.26%)
Mutual labels:  eloquent, model
Befriended
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Stars: ✭ 596 (+1822.58%)
Mutual labels:  eloquent, model
Plans
Laravel Plans is a package for SaaS apps that need management over plans, features, subscriptions, events for plans or limited, countable features.
Stars: ✭ 326 (+951.61%)
Mutual labels:  eloquent, model
acorn-db
Provides Acorn projects with Eloquent Models for WordPress data.
Stars: ✭ 30 (-3.23%)
Mutual labels:  eloquent, model
Laravel Model Status
Easily add statuses to your models
Stars: ✭ 510 (+1545.16%)
Mutual labels:  eloquent, model
Guardian
Eloquent Guardian is a simple permissions system for your users. While there are many other packages for permissions, this one solves everything in the most eloquent way.
Stars: ✭ 121 (+290.32%)
Mutual labels:  eloquent, model
Elasticsearch
The missing elasticsearch ORM for Laravel, Lumen and Native php applications
Stars: ✭ 375 (+1109.68%)
Mutual labels:  eloquent, model
eloquent-filemaker
A Model extension and Eloquent driver for Laravel connecting to FileMaker through the Data API
Stars: ✭ 38 (+22.58%)
Mutual labels:  eloquent, model
Rating
Laravel Eloquent Rating allows you to assign ratings to any model.
Stars: ✭ 175 (+464.52%)
Mutual labels:  eloquent, model
attribute-events
🔥 Fire events on attribute changes of your Eloquent model
Stars: ✭ 198 (+538.71%)
Mutual labels:  eloquent, attributes
laravel-geoly
Perform fast and efficient radius searches on your Laravel Eloquent models.
Stars: ✭ 25 (-19.35%)
Mutual labels:  eloquent, model
Laravel Sluggable
An opinionated package to create slugs for Eloquent models
Stars: ✭ 831 (+2580.65%)
Mutual labels:  eloquent, model
Schedule
Schedule is a package that helps tracking schedules for your models. If you have workers in a company, you can set schedules for them and see their availability though the time.
Stars: ✭ 155 (+400%)
Mutual labels:  eloquent, model
db-safedelete
Attempts to invoke force delete, if it fails - falls back to soft delete
Stars: ✭ 16 (-48.39%)
Mutual labels:  eloquent, model
laravel-route-model-autobinding
THIS PACKAGE HAS BEEN DEPRECATED — Automatically bind Eloquent models as route segment variables.
Stars: ✭ 14 (-54.84%)
Mutual labels:  eloquent, model
lmkit
language models toolkits with hierarchical softmax setting
Stars: ✭ 16 (-48.39%)
Mutual labels:  model
virgil-sdk-net
Virgil Core SDK allows developers to get up and running with Virgil Cards Service API quickly and add end-to-end security to their new or existing digital solutions to become HIPAA and GDPR compliant and more.
Stars: ✭ 16 (-48.39%)
Mutual labels:  gdpr
model-observers
Make model observers easy
Stars: ✭ 17 (-45.16%)
Mutual labels:  eloquent
dotobj
.obj/.mtl loader, written in native GML, for GameMaker Studio 2.3
Stars: ✭ 27 (-12.9%)
Mutual labels:  model

Convert Eloquent boolean attributes to dates (and back)

Latest stable release Software license Build status Total downloads Total stars

Read my blog View my other packages and projects Follow @sebastiaanluca on Twitter Share this package on Twitter

Automatically convert Eloquent model boolean fields to dates (and back to booleans) so you always know when something was accepted or changed.

Say you've got a registration page for users where they need to accept your terms and perhaps can opt-in to certain features using checkboxes. With the new(-ish) GDPR privacy laws, you're somewhat required to not just keep track of the fact if they accepted those (or not), but also when they did.

Example

User registration controller:

$input = request()->input();

$user = User::create([
    'has_accepted_terms' => $input['terms'],
    'is_subscribed_to_newsletter' => $input['newsletter'],
]);

Anywhere else in your code:

// true or false (boolean)
$user->has_accepted_terms;

// 2018-05-10 16:24:22 (Carbon instance)
$user->accepted_terms_at;

Table of contents

Requirements

  • PHP 8 or 8.1
  • Laravel ^9.2

How to install

Add the package to your project using composer:

composer require sebastiaanluca/laravel-boolean-dates

Set up your Eloquent model by:

  1. Adding your datetime columns to $casts
  2. Adding the boolean attributes to $appends
  3. Creating attribute accessors and mutators for each field
<?php

declare(strict_types=1);

use Illuminate\Database\Eloquent\Model;
use SebastiaanLuca\BooleanDates\BooleanDateAttribute;

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'accepted_terms_at' => 'immutable_datetime',
        'subscribed_to_newsletter_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array<int, string>
     */
    protected $appends = [
        'has_accepted_terms',
        'is_subscribed_to_newsletter',
    ];

    protected function hasAcceptedTerms(): Attribute
    {
        return BooleanDateAttribute::for('accepted_terms_at');
    }

    protected function isSubscribedToNewsletter(): Attribute
    {
        return BooleanDateAttribute::for('subscribed_to_newsletter_at');
    }
}

Optionally, if your database table hasn't got the datetime columns yet, create a migration to create a new table or alter your existing table to add the timestamp fields:

<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::table('users', static function (Blueprint $table): void {
            $table->timestamp('accepted_terms_at')->nullable();
            $table->timestamp('subscribed_to_newsletter_at')->nullable();
        });
    }
};

How to use

Saving dates

If a boolean date field's value is true-ish, it'll be automatically converted to the current datetime. You can use anything like booleans, strings, positive integers, and so on.

$user = new User;

// Setting values explicitly
$user->has_accepted_terms = true;
$user->has_accepted_terms = 'yes';
$user->has_accepted_terms = '1';
$user->has_accepted_terms = 1;

// Or using attribute filling
$user->fill(['is_subscribed_to_newsletter' => 'yes']);

$user->save();

All fields should now contain a datetime similar to 2018-05-10 16:24:22.

Note that the date stored in the database column is immutable, i.e. it's only set once. Any following updates will not change the stored date(time), unless you update the date column manually or if you set it to false and back to true (disabling, then enabling it).

For example:

$user = new User;

$user->has_accepted_terms = true;
$user->save();

// `accepted_terms_at` column will contain `2022-03-13 13:20:00`

$user->has_accepted_terms = true;
$user->save();

// `accepted_terms_at` column will still contain the original `2022-03-13 13:20:00` date

Clearing saved values

Of course you can also remove the saved date and time, for instance if a user retracts their approval:

$user = User::findOrFail(42);

$user->has_accepted_terms = false;
$user->has_accepted_terms = null;
$user->has_accepted_terms = '0';
$user->has_accepted_terms = 0;
$user->has_accepted_terms = '';
// $user->has_accepted_terms = null;

$user->save();

False or false-y values are converted to NULL.

Retrieving values

Retrieving fields as booleans

Use a boolean field's defined key to access its boolean value:

$user = User::findOrFail(42);

// true or false (boolean)
$user->has_accepted_terms;

Retrieving fields as datetimes

Use a boolean field's defined value to explicitly access its (Carbon) datetime value:

$user = User::findOrFail(42);

// 2018-05-10 16:24:22 (Carbon or CarbonImmutable instance)
$user->accepted_terms_at;

// null
$user->is_subscribed_to_newsletter;

Array conversion

When converting a model to an array, the boolean fields will be included if you've added them to the $appends array in your model.

$user = User::findOrFail(42);

$user->toArray();

/*
 * Which will return something like:
 * 
 * [
 *     'accepted_terms_at' => \Carbon\CarbonImmutable('2018-05-10 16:24:22'),
 *     'subscribed_to_newsletter_at' => \Illuminate\Support\Carbon('2018-05-10 16:24:22'),
 *     'has_accepted_terms' => true,
 *     'is_subscribed_to_newsletter' => true,
 * ];
 */

License

This package operates under the MIT License (MIT). Please see LICENSE for more information.

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

composer install
composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

About

My name is Sebastiaan and I'm a freelance back-end developer specializing in building custom Laravel applications. Check out my portfolio for more information, my blog for the latest tips and tricks, and my other packages to kick-start your next project.

Have a project that could use some guidance? Send me an e-mail at [email protected]!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].