Resolvable
Make your Eloqeunt models resolvable by more than their key., (*1)
Models will be resolved from an instance of the same Model, the primary key or any of the fields specified in the $resolvable
variable., (*2)
This saves the requirement to list multiple where()
statements to locate the correct Model, or where the data parameter can vary., (*3)
Usage
Import the Resolvable trait to your model and define your resolvable fields. (The primary key field on your Model is automatically included during resolution), (*4)
<?php
namespace App\Models;
use JournoLink\Resolvable\Resolvable;
use Illuminate\Database\Eloquent\Model;
class Thing extends Model
{
use Resolvable;
/**
* An array of field names that the Model can be resolved from
*
* @var array
*/
protected $resolvable = ['name'];
...
}
Call the resolve()
static method to resolve an instance from your parameter., (*5)
// Thing {
// id: 1
// name: "My Thing"
// value: 123.45
// }
// All 3 will return the same Model
$thing1 = Thing::resolve(1);
$thing2 = Thing::resolve('My Thing');
$thing3 = Thing::resolve($thing1);
// This will return null as "value" isn't in the $resolvable array
$thing4 = Thing::resolve(123.45);