Looking to hire Laravel developers? Try LaraJobs

laravel-composite-key maintained by laravel-composite-key

Description
Adds full native-style Composite Primary Key support to Eloquent Models
Author
Laravel Composite Key Contributors
Last update
2026/05/11 22:24 (dev-main)
License
Links
Downloads
6

Comments
comments powered by Disqus

Laravel Composite Primary Key

Latest Version on Packagist License

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

Requirements

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

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

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

The package will automatically register its service provider.

Usage

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

// 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

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

Updating Records

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

Deleting Records

$userRole->delete();

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

// 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

Method Description
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 binding

Query Builder Macros

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

Macro Description
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 key

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

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

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

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

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

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

License

The MIT License (MIT). Please see License File for more information.