journolink/resolvable

Make Eloquent models resolvable by fields other than the primary key

1.0.1 2018-07-07 20:46 UTC

This package is auto-updated.

Last update: 2024-11-04 21:37:25 UTC


README

Make your Eloqeunt models resolvable by more than their key.

Models will be resolved from an instance of the same Model, the primary key or any of the fields specified in the $resolvable variable.

This saves the requirement to list multiple where() statements to locate the correct Model, or where the data parameter can vary.

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)

<?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.

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