Laravel insert embedsOne from existing collection

Viewed 83

In my project, I use Laravel 8 with Mongodb as my database, and jenssegers/laravel-mongodb as its driver. Let say I have a collection named products which has relationship embedsOne to vendors. when I create a new product, how can I insert existing vendor to this new product? I tried the following

$vendor = Vendor::find($request->vendor);
$product = Product::create([
    'name'=>$request->name
    'vendor'=>$vendor
]);

which resulting the following document.

{
    "_id": "606ffac287be2020b968c613",
    "name": "product name",
    "vendor": {
        "incrementing": true,
        "exists": true,
        "wasRecentlyCreated": false,
        "timestamps": true
    },
    "updated_at": "2021-04-09T06:57:06.032000Z",
    "created_at": "2021-04-09T06:57:06.032000Z"
}

I also tried to insert the vendor just like in the documentation said:

$vendor = Vendor::find($request->vendor);
$product = Product::create([
    'name'=>$request->name
]);

$product->vendor()->save($vendor);

but that way the vendor does not saved at all. so, what is the correct way to insert existing vendor to product?

1 Answers

Sorry! I know its been a year but though I'd share for anyone with a similar problem since I was struggling with the same issue. I solved it!!!

I found the culprit. So my use case is that a User embeds many vehicles.

class User extends Authenticatable {

use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

protected $fillable = [
    'name','firstname', 'lastname', 'email', 'mobile', 
    'password',     
    'pushtoken', 'is_company_billpayer',
    'addresses', 'picture', 'company_id', 'is_company_billpayer', 
    'deleted_at', 'membership_id'
];

public function vehicles()
{
    return $this->embedsMany(Vehicle::class);
}

}

In the class which will be embeded, i.e. the Vehicle the document, you haven't declared the _id in the $fillable array thats why you cannot embed the document with the same id.

class Vehicle extends Model {

protected $collection = 'vehicles';

protected $fillable = ['_id', 'make', 'model', 'regno', 'colour', 
                       'pictures', 'users'];

then when embedding, just add the _id like so;

if ($request_data['vehicle_id'] != null){

$saved_user->vehicles()->create([
    '_id' => new \MongoDB\BSON\ObjectID($vehicle->_id), 
    'make' => $vehicle->make, 'model' => $vehicle->model,
    'regno' => $vehicle->regno, 'colour' => $vehicle->colour, 
    'pictures' => $vehicle->pictures
]);

}

Hope that helps. It worked for me.

Related