thiagoprz / eloquent-composite-key
Eloquent Composite Key Support Package
Installs: 113 654
Dependents: 1
Suggesters: 0
Security: 0
Stars: 50
Watchers: 3
Forks: 6
Open Issues: 1
Requires
- php: ^7.1 || ^8.0 || ^8.1
Requires (Dev)
- orchestra/testbench: 6
- squizlabs/php_codesniffer: 4.0.x-dev
This package is auto-updated.
Last update: 2024-10-24 02:51:44 UTC
README
Package to enable composite key support on Eloquent Models.
Installation
Install it with composer:
composer require thiagoprz/eloquent-composite-key
Usage
Define the primaryKey as an array and use the HasCompositeKey trait on your model class.
<?php
...
use Thiagoprz\CompositeKey\HasCompositeKey;
class User extends Model
{
use HasCompositeKey;
...
protected $primaryKey = ['firstKey', 'secondKey'];
...
}
Using primary keys to find records:
<?php
...
// Returns model instance or null
$user = User::find([
'key_1' => $key1,
'key_2' => $key2,
]);
...
// Throws ModelNotFoundException
$user = User::findOrFail([
'key_1' => $key1,
'key_2' => $key2,
]);
...
The main idea of this package is to allow Laravel projects use composite keys on models despite Eloquent not supporting them officially (see https://laravel.com/docs/8.x/eloquent#composite-primary-keys).