phplaravelmongodbuuidjenssegers-mongodb

Laravel MongoDB pass object in model


My current MongoDB schema is using a custom UUID object type as _id. I'm trying to generate a new UUID in my User model using $attributes = [];. I can't find any solution on how I can pass an object data type into my model.

My model :

use Authenticatable, Authorizable, CanResetPassword;

protected $connection = 'mongodb';
protected $collection = 'users';

protected $fillable = [
    'username', 'email', 'password'
];

protected $attributes = [
    '_id' => Uuid\Uuid::uuid4(),
    'rank' => 1,
    'token' => 0,
    'banned' => false,
    'vote_count' => 0,
    'vote_bank' => 0,
    'capeAllowed' => false,
    'skin' => null,
    'cape' => null,
    'verified' => false,
    'nameChanges' => 0
];

I can't find a way to have my object UUID into _id. It has to be an object type and not a string.

I have tried doing it by passing a new object using the User::create(Uuid::uuidv4()) but it doesn't take it either. The webserver used to be on NodeJS which didn't have any problem using object as data type. The database has already many records using a UUID Binary object as the _id.

I have also tried using many library. Many don't work with Laravel 6.x or the ones that work doesn't return a binary format.


Solution

  • The solution was using the User::create() method. The protected $attributes = [] doesn't accept variables from what I could see. I used PHP's Binary class to convert ramsey/uuidv4 as a UUID type : new Binary(Uuid::uuid4()->getBytes(), Binary::TYPE_UUID)