PHP code example of fanmade / laravel-bitwise-trait

1. Go to this page and download the library: Download fanmade/laravel-bitwise-trait 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/ */

    

fanmade / laravel-bitwise-trait example snippets


$table->unsignedTinyInteger('status');   // 1 byte  -> up to 8 flags
$table->unsignedSmallInteger('status');  // 2 bytes -> up to 16 flags
$table->unsignedMediumInteger('status'); // 3 bytes -> up to 24 flags
$table->unsignedInteger('status');       // 4 bytes -> up to 32 flags



namespace App\Models;

use Fanmade\Bitwise\BitwiseFlagTrait;
use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    use BitwiseFlagTrait;

    public const SENT     = 1 << 0; // 1
    public const RECEIVED = 1 << 1; // 2
    public const SEEN     = 1 << 2; // 4
    public const READ     = 1 << 3; // 8
}

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function seen(): Attribute
{
    return Attribute::make(
        get: fn (): bool => $this->getFlag('status', self::SEEN),
        set: fn (bool $value) => $this->setFlag('status', self::SEEN, $value),
    );
}

$message->seen = true;
$message->seen; // => true
$message->save();

public function getSeenAttribute(): bool
{
    return $this->getFlag('status', self::SEEN);
}

public function setSeenAttribute(bool $value): void
{
    $this->setFlag('status', self::SEEN, $value);
}

use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;

#[Scope]
protected function read(Builder $query): void
{
    $query->whereRaw('(status & ?) = ?', [self::READ, self::READ]);
}

#[Scope]
protected function unread(Builder $query): void
{
    $query->whereRaw('(status & ?) = 0', [self::READ]);
}

Message::read()->get();
Message::unread()->get();

public function scopeRead(Builder $query): Builder
{
    return $query->whereRaw('(status & ?) = ?', [self::READ, self::READ]);
}

public function scopeUnread(Builder $query): Builder
{
    return $query->whereRaw('(status & ?) = 0', [self::READ]);
}

public const SENT = 8;         // decimal
public const SENT = 1 << 3;    // bit shift
public const SENT = 0b0001000; // binary literal