5

Is there any database similiar to bit (byte) in laravel, could not find any in the documentation. (https://laravel.com/docs/5.1/migrations).

I try to do something like:

00000001 -> stands for something lets say playstation

00000010 -> stands for xbox

00000011 -> stands for both above
1

1 Answer 1

2

Instead of trying to use the BIT datatype, which would be a bit of a hassle to work with, you can just use an integer and bitwise operators instead, assuming you don't need more than 32 options for one field (bigint = 8 bytes = 32 bits).

As a very simple example, imagine you create the following enum class:

class Bitmask {
    const ATARI       = 1 << 0; // 00000001 (1)
    const NES         = 1 << 1; // 00000010 (2)
    const SNES        = 1 << 2; // 00000100 (4)
    const SEGA        = 1 << 3; // 00001000 (8)
    const PLAYSTATION = 1 << 4; // 00010000 (16)
    const XBOX        = 1 << 5; // 00100000 (32)
}

To set the field, all you need to do is add the bitmasks together (in this configuration, ORing (|) them is the same). If a user has an NES and a PLAYSTATION:

$user->systems = Bitmask::NES + Bitmask::PLAYSTATION;

To query, you would use the bitwise operators. So, if you wanted the users that have SEGAs:

User::where('systems', '&', Bitmask::SEGA)->get();

If you wanted the users that have PLAYSTATIONs or XBOXes:

User::where('systems', '&', Bitmask::PLAYSTATION | Bitmask::XBOX)->get();

The & operator will perform a bitwise AND operation between the integer field and the integer you pass in. If any of the bits match up, the & operator will return a value > 0, and the where clause will be truthy. If none of the bits match up, the & operator will return 0 and the where clause will be false.

Sign up to request clarification or add additional context in comments.

2 Comments

FYI, "a bit of a hassle to work with...", no pun intended. :)
@AlexOxilg Any particular reason you removed this from being the accepted answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.