cmdobueno's avatar

Route Model Binding Resolve

Back Story: This system uses multiple databases to store what could effectively be called cached data. When a new quote is created, the system data is cloned for the quote specifically so that pricing will never change (thats the super simple break down of it).

I have added the ability to customize this data within a quote, so if you needed to update the price of a material, it could easily be done rather than being forced to generate a new quote. In doing this I found that Route Model Binding would fail, as it looked in the Primary database rater than the selected child database.

I wrote this section of code, and would really like a little feedback on how i could make it "better". I went with route segments because I do not the ability to DD (this is an API... so DD always breaks for me).

/**
 * @param mixed $value
 * @return Model|null
*/
public function resolveRouteBinding($value)
{
    if (\Request::segment(2) === 'quotes') {
        //We need to modify our query to a different database.
        $quote = Quote::find(\Request::segment(3));
        change_database($quote->db_name);
        $results = $this->where($this->getRouteKeyName(), $value)->first();
        change_database();
    } else {
        $results = $this->where($this->getRouteKeyName(), $value)->first();
    }
    return $results;
}

0 likes
1 reply
bugsysha's avatar

Is Quote a model in your app? If so then why don't you just set the connection on that model (if databases are on different servers) or database (if databases are on the same server) and that is it?

protected $connection = 'connection-name';

I do not see anything in documentation about database property on a model, so maybe there isn't such a feature, but still it can be achieved with connection.

Please or to participate in this conversation.