Skip to content

Route Key Trait to use Optimus in models #5

Closed
@ivanvermeyen

Description

Hello,

I'm playing around with various Optimus packages for Laravel at the moment.
I really like how yours is set up, with the different connections etc. and your code looks very clean!
I love it :D

I was looking for the easiest way to get the encoded ID's into my models, without having to duplicate route bindings and all. This is what I ended up with... Maybe this can go into a Trait that can be part of your package? What do you think?

/**
 * Get the value of the model's route key.
 *
 * @return mixed
 */
public function getRouteKey()
{
    $id = parent::getRouteKey();

    return $this->getOptimus()->encode($id);
}

/**
 * Retrieve the model for a bound value.
 *
 * @param mixed $value
 *
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value)
{
    $id = $this->getOptimus()->decode($value);

    return $this->where($this->getRouteKeyName(), $id)->first();
}

/**
 * Get the Optimus instance.
 *
 * @return \Cog\Laravel\Optimus\OptimusManager
 */
protected function getOptimus()
{
    $connection = null;

    if (property_exists($this, 'optimusConnection')) {
        $connection = $this->optimusConnection;
    }

    return \Cog\Laravel\Optimus\Facades\Optimus::connection($connection);
}

People configure the primes in your config file, and they can define a connection name on a specific model by setting a $optimusConnection property. If they don't, the default connection is used.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions