tassawartech174/mongodb-relations

Custom Laravel Eloquent relationships for MongoDB using jenssegers/mongodb and mongodb/laravel-mongodb. Supports unidirectional many-to-many and reverse lookups for embedded and reference-based relations.

v1.1.5 2025-07-07 13:44 UTC

This package is auto-updated.

Last update: 2025-07-07 13:45:07 UTC


README

License: MIT

Custom unidirectional many-to-many relationship support for MongoDB in Laravel.

📦 Installation

composer require tassawartech174/mongodb-relations

Requires PHP 7.4+ and Laravel 6.x – 11.x.

⚙️ Configuration

If you want to customize the default local key used in relations, publish the package config file:

php artisan vendor:publish --provider="TassawarTech174\MongodbRelations\MongodbRelationsServiceProvider" --tag=mongodb-relations-config

Or use this command:

php artisan vendor:publish --tag=mongodb-relations-config
  • This will publish:
config/mongodb-relations.php

🚀 Usage

Step 1: Use the Trait

In your Eloquent model (e.g. User), use the provided trait:

use TassawarTech174\MongodbRelations\Traits\MongodbRelations;

class User extends Model
{
    use MongodbRelations;

    public function roles()
    {
        return $this->manyToManyRelation(Role::class, 'role_ids');
    }
}

Or use relation like:

use TassawarTech174\MongodbRelations\Traits\MongodbRelations;

class User extends Model
{
    use MongodbRelations;

    public function roles()
    {
        return $this->manyToManyRelation(Role::class);
    }
}

Step 3: Relationship Methods

  • Get related models:
$user->roles;
  • Attach related models:
$user->roles()->attach(['id1', 'id2']);
  • Detach related models:
$user->roles()->detach(['id1']);
  • Sync related models:
$user->roles()->sync(['id1', 'id3']);
  • Models where relations:
$user->whereRelationField('roles', 'name', 'operater', 'search value);

$user->orWhereRelationField('roles', 'name', 'operater', 'search value);

✅ Supported Laravel Versions

  • Laravel 6.x

  • Laravel 7.x

  • Laravel 8.x

  • Laravel 9.x

  • Laravel 10.x

  • Laravel 11.x

🔐 License

This package is open-source software licensed under the MIT license.