PHP code example of sebastiaanluca / laravel-boolean-dates
1. Go to this page and download the library: Download sebastiaanluca/laravel-boolean-dates library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sebastiaanluca / laravel-boolean-dates example snippets
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');
}
}
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();
});
}
};
$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();
$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