PHPackages                             laravel-composite-key/laravel-composite-key - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. laravel-composite-key/laravel-composite-key

ActiveLibrary[Database &amp; ORM](/categories/database)

laravel-composite-key/laravel-composite-key
===========================================

Adds full native-style Composite Primary Key support to Eloquent Models

v1.0.2(4w ago)03MITPHPPHP ^8.2CI failing

Since May 11Pushed 4w agoCompare

[ Source](https://github.com/Louai773/laravel-composite-key)[ Packagist](https://packagist.org/packages/laravel-composite-key/laravel-composite-key)[ RSS](/packages/laravel-composite-key-laravel-composite-key/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (7)Versions (4)Used By (0)

Laravel Composite Primary Key
=============================

[](#laravel-composite-primary-key)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c353534a77466d04193502594903aa8243e23f53a9ff883a9f2dd656ea0b6ccc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c61726176656c2d636f6d706f736974652d6b65792f6c61726176656c2d636f6d706f736974652d6b65792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/laravel-composite-key/laravel-composite-key)[![License](https://camo.githubusercontent.com/850eae1099d2b05f53383473d7cd51f9bc1ab09b7d0d9e5122f1dd930efdcc6d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d6173686170652f6170697374617475732e737667)](https://packagist.org/packages/laravel-composite-key/laravel-composite-key)

Adds full native-style Composite Primary Key support to Eloquent Models.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10.0+ (Laravel 11, 12, 13 compatible)

Supported Databases
-------------------

[](#supported-databases)

The package is tested and works with:

- **SQLite** (primary testing)
- **MySQL / MariaDB**
- **PostgreSQL**
- **SQL Server**
- **Oracle**

All databases use Laravel's unified query builder abstraction, ensuring consistent behavior across platforms.

Installation
------------

[](#installation)

```
composer require laravel-composite-key/laravel-composite-key
```

The package will automatically register its service provider.

Usage
-----

[](#usage)

### Basic Model Setup

[](#basic-model-setup)

```
use Laravel\CompositeKey\HasCompositePrimaryKey;
use Illuminate\Database\Eloquent\Model;

class UserRole extends Model
{
    use HasCompositePrimaryKey;

    protected $primaryKey = ['user_id', 'role_id'];
    public $incrementing = false;
    protected $fillable = ['user_id', 'role_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }
}
```

### Finding Records

[](#finding-records)

```
// Using find() with array (recommended)
$userRole = UserRole::find([1, 5]);
$userRole = UserRole::findOrFail([1, 5]);

// Find multiple records
$userRoles = UserRole::findMany([[1, 1], [1, 2], [2, 3]]);

// Using where with array
$userRole = UserRole::where([
    'user_id' => 1,
    'role_id' => 5,
])->first();

// Using whereCompositeKey macro
$userRole = UserRole::whereCompositeKey([1, 5])->first();
```

> **Note:** The `find()` method accepts an array of values corresponding to the order of your `$primaryKey` array. For `['user_id', 'role_id']`, use `find([1, 5])` where `1` is `user_id` and `5` is `role_id`.

### Creating Records

[](#creating-records)

```
$userRole = new UserRole();
$userRole->user_id = $user->id;
$userRole->role_id = $role->id;
$userRole->save();
```

### Updating Records

[](#updating-records)

```
$userRole->update(['user_id' => $user->id]);
```

### Deleting Records

[](#deleting-records)

```
$userRole->delete();
```

### Route Model Binding

[](#route-model-binding)

```
// Generate route key with separator (e.g., "1:5")
$routeKey = $userRole->getRouteKeyWithSeparator(':');

// In your routes
Route::get('user-roles/{userRole}', function (UserRole $userRole) {
    return $userRole;
});

// URL: /user-roles/1:5
```

### Eager Loading Relationships

[](#eager-loading-relationships)

```
// Load with relationships
$userRole = UserRole::with('role')->find([1, 5]);

// Load multiple with relationships
$userRoles = UserRole::with('role')->findMany([[1, 1], [2, 2]]);
```

Key Methods
-----------

[](#key-methods)

MethodDescription`newEloquentBuilder()`Returns `CompositeKeyBuilder` for `find([...])` support`getKeyName()`Returns primary key name(s) as array or string`getKey()`Returns primary key value(s)`usesCompositePrimaryKey()`Check if model uses composite keys`getCompositeKeyNames()`Get composite key names array`getCompositeKeyValues()`Get composite key values array`getRouteKeyName()`Returns underscore-joined key names`getRouteKeyWithSeparator($separator)`Returns values joined by separator`resolveRouteBinding($value)`Resolve model from separator-formatted bindingQuery Builder Macros
--------------------

[](#query-builder-macros)

The package registers the following macros on `Illuminate\Database\Eloquent\Builder`:

MacroDescription`whereCompositeKey($values)`Query by composite key values`orWhereCompositeKey($values)`OR query by composite key`whereNotCompositeKey($values)`NOT query by composite key`orWhereNotCompositeKey($values)`OR NOT query by composite keyExtended Relationship Classes
-----------------------------

[](#extended-relationship-classes)

The package includes extended relationship classes for composite key support:

- `Laravel\CompositeKey\CompositeBelongsTo`
- `Laravel\CompositeKey\CompositeHasMany`
- `Laravel\CompositeKey\CompositeHasOne`
- `Laravel\CompositeKey\CompositeBelongsToMany`
- `Laravel\CompositeKey\CompositePivot`

These classes handle relationships where foreign keys may be part of a composite key.

Migration Examples
------------------

[](#migration-examples)

### SQLite / MySQL / PostgreSQL

[](#sqlite--mysql--postgresql)

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->timestamps();

            $table->primary(['user_id', 'role_id']);
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('role_id')->references('id')->on('roles');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('user_roles');
    }
};
```

### SQL Server

[](#sql-server)

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->timestamps();

            $table->primary(['user_id', 'role_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('user_roles');
    }
};
```

### Oracle

[](#oracle)

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();

            $table->primary(['user_id', 'role_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('user_roles');
    }
};
```

Testing
-------

[](#testing)

```
cd laravel-composite-key
composer install
vendor/bin/phpunit tests/
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email the maintainers.

Credits
-------

[](#credits)

- [Laravel Composite Key Contributors](https://github.com/laravel-composite-key/laravel-composite-key/graphs/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance94

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

29d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d4532a60907c945908da39ab43e43bb590bbf196dae2f21bacd7434d2555afc6?d=identicon)[Louai773](/maintainers/Louai773)

---

Top Contributors

[![Louai77](https://avatars.githubusercontent.com/u/50366921?v=4)](https://github.com/Louai77 "Louai77 (3 commits)")

---

Tags

laraveldatabaseeloquentcompositeprimary key

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/laravel-composite-key-laravel-composite-key/health.svg)

```
[![Health](https://phpackages.com/badges/laravel-composite-key-laravel-composite-key/health.svg)](https://phpackages.com/packages/laravel-composite-key-laravel-composite-key)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.0M84](/packages/mongodb-laravel-mongodb)[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k29.9M42](/packages/kirschbaum-development-eloquent-power-joins)[watson/validating

Eloquent model validating trait.

9743.4M53](/packages/watson-validating)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

592452.8k2](/packages/spiritix-lada-cache)[aimeos/laravel-nestedset

Nested Set Model for Laravel

379.9k5](/packages/aimeos-laravel-nestedset)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
