定制 sebastiaanluca/laravel-boolean-dates 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sebastiaanluca/laravel-boolean-dates

Composer 安装命令:

composer require sebastiaanluca/laravel-boolean-dates

包简介

Automatically convert Eloquent model boolean attributes to dates (and back).

README 文档

README

Latest stable release Software license Total downloads Total stars

Visit my website 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 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.4 or 8.5
  • Laravel 11 or 12

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 the $casts property or casts() method
  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 hello@sebastiaanluca.com 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 web apps. Check out my website for more information and my other packages to kick-start your next project.

Have a project that could use some guidance? Send me an e-mail at hello@sebastiaanluca.com!

sebastiaanluca/laravel-boolean-dates 适用场景与选型建议

sebastiaanluca/laravel-boolean-dates 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 116.37k 次下载、GitHub Stars 达 40, 最近一次更新时间为 2018 年 07 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「convert」 「model」 「laravel」 「eloquent」 「boolean」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sebastiaanluca/laravel-boolean-dates 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sebastiaanluca/laravel-boolean-dates 我们能提供哪些服务?
定制开发 / 二次开发

基于 sebastiaanluca/laravel-boolean-dates 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 116.37k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 40
  • 点击次数: 34
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 40
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-07-26