首页 > 解决方案 > 如何根据 laravel 上博客文章的 user_id 显示用户的照片?

问题描述

这是我的 index.blade.php

<img class="img-circle img-bordered-sm" src="{{$user->photo_id ? $user->photo->file : 'http://placehold.it/100x100'}}" alt="user image">

标签: phplaravel-5

解决方案


在后期模型中添加:

public function getWriterAvatarAttribute(){
    try {
        return User::findOrFail($this->user_id)->photo->file;
    } catch (ModelNotFoundException $e){
        return 'http://placehold.it/100x100';
    }
}

并认为:

<img src="{{$post->writer_avatar}}" alt="user image">

推荐阅读