Laravel relationship "fallback"

Viewed 484
class Price extends Model {
    public function priceable() {
        return $this->morphTo();
    }
}

class Venue extends Model {
    public function events() {
        return $this->hasMany('App\Event');
    }
    public function price() {
        return $this->morphOne('App\Price', 'priceable');
    }
}

class Event extends Model {
    public function venue() {
        return $this->belongsTo('App\Venue');
    }
    public function price() {
        return $this->morphOne('App\Price', 'priceable');
    }
}

What is the best way to have a fallback, if the event doesn't have a price assigned, to get it to use the event's venue price? Is there a logical way to make this as a relation or should I just do everything in the Controllers?

2 Answers

You can set a default model with optional custom values directly from the relation. This default model can be populated either from an array or an anonymous function:

public function price()
{
    return $this->morphOne('App\Price', 'priceable')->withDefault([...]);
}

You can refer to Laravel's documentation about default models for some more explanation.

class Event extends Model {
...
    public function getEventPriceAttribute() {
        return $this->price > 0 ? $this->price : $this->venue()->price
    }
...
}

By doing this, you can call Event object and get the price like this:

$eventObject->eventPrice;
Related