Laravel Eloquent setting a default value for a model relation?

让人想犯罪 __ 提交于 2019-12-06 03:43:35

You could create an accessor on the Product model that did the check for you. Works the same if you just wanted to define it as a method, also (good for if you want to abstract some of the Eloquent calls, use an interface for your Product in case you change it later, etc.)

/**
 * Create a custom thumbnail "column" accessor to retrieve this product's
 * photo, or a default if it does not have one.
 * 
 * @return string
 */
public function getThumbnailAttribute()
{
    $default = $this->defaultPhoto;

    return ( ! is_null($default))
        ? $default->thumb
        : '/products/default/thumb.jpg';
}

You might also want to look into Presenters. A bit overkill for some situations, but incredibly handy to have (and abstract things like this away from your models).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!