Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laravel 9.31.0 does not generate IDs anymore #2451

Closed
fosron opened this issue Sep 21, 2022 · 2 comments
Closed

Laravel 9.31.0 does not generate IDs anymore #2451

fosron opened this issue Sep 21, 2022 · 2 comments

Comments

@fosron
Copy link

fosron commented Sep 21, 2022

None of my models seem to generate mongodb IDs anymore. I'm trying to figure out what's happening, but to no avail at the moment.

<?php

class Message extends \Jenssegers\Mongodb\Eloquent\Model
{ 
    use \Illuminate\Database\Eloquent\Factories\HasFactory, \Jenssegers\Mongodb\Eloquent\HybridRelations;
    protected $connection = 'mongodb';

    protected $collection = 'messages';
}
$message = new Message();
$message->save();

$message->getKey();
// null

$message->getKeyName();
// _id
@fosron
Copy link
Author

fosron commented Sep 21, 2022

I have to add this trait for the ID to generate, can not yet make sure if it works properly - like does it add it to relations, does Mongo get proper ObjectID type when data is inserted.

Code is influenced by HasUuid concern from Laravel 9.x

<?php

use Illuminate\Support\Str;
use MongoDB\BSON\ObjectId;

trait HasMongoIds
{
    /**
     * Generate a primary MongoID for the model.
     *
     * @return void
     */
    public static function bootHasMongoIds()
    {
        static::creating(function (self $model) {
            if ($model->getKeyName() === '_id' && !$model->getKey()) {
                $model->setAttribute('_id', new ObjectID);
            }
        });
    }
}

@fosron
Copy link
Author

fosron commented Sep 23, 2022

Issue should be fixed in the next framework release laravel/framework#44247

@fosron fosron closed this as completed Sep 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant