【问题标题】:How to attach image path on getting data from database using laravel如何在使用 laravel 从数据库中获取数据时附加图像路径
【发布时间】:2019-11-30 13:56:57
【问题描述】:

我正在从数据库中获取数据,并且我有一个字段 profile_pic,我正在将图像名称保存在我的数据库中,我的响应如下所示:

"basicInfo": {
    "id": 205,
    "first_name": "new name",
    "middle_name": "middle",
    "profile_pic": "3q4Vs8iHdY.png",            
}

如您所见,profile_pic 我正在获取图像名称和存储图像的文件夹 public/profile_images,当我点击获取 Api 时,我得到了 profile_pic 中图像名称的响应。 但我想通过附加来自 public/profile_images 的路径来获得我的回复的完整路径:

我收到此响应的代码

$userBasicInfo = $this->userBasicInfo->where('user_id', $user_id)->first();

这会获取所有数据,但我也想在我的 profile_pic 中附加图像路径名 我怎么能这样做? 我被困在这里了

class UserBasicInfo extends Model
{
    use SoftDeletes;

    const DELETED_AT = 'deletedAt';
    protected $table = "user_basic_info";

    protected $fillable = [
        'first_name','city','state','zip','social_security','middle_name', 'last_name', 'profile_pic', 'date_of_birth', 'gender', 'area_id', 'user_id', 'created_by', 'updated_by', 'created_at', 'deletedAt','title','cell_no','address','work_phone','fax','extension','primary_facility','affiliated_facility','employed_by','emergency_phone','designation','department','employment_type','biography','hiring_date','from','to'
    ];

    protected $hidden = ['deletedAt'];

    function user() {
        return $this->belongsTo('App\User', 'id', 'user_id');
    }

    public function getFromAttribute($value){
        $createdAt= Carbon::parse($value);
        return $createdAt->toIso8601String();
    }

    public function getToAttribute($value){
        $createdAt= Carbon::parse($value);
        return $createdAt->toIso8601String();
    }
}


if (!empty($userBasicInfo->profile_pic)){
    $deleteImage =$userBasicInfo->profile_pic;
    unlink(public_path('profile_images').'/'.$deleteImage);
}

【问题讨论】:

    标签: php laravel image public


    【解决方案1】:

    您可以在 UserBasicInfo 模型中使用访问器:

    public function getProfilePicAttribute($value)
    {
        return 'path/to/image' . $value;
    }
    

    来自 laravel 文档的访问器指南:

    https://laravel.com/docs/5.8/eloquent-mutators#defining-an-accessor

    【讨论】:

    • 我已经分享了我的 userBasicinfo 模型,您可以在那里查看并添加逻辑,您的帮助将不胜感激
    • 只需添加我上面写的功能,它应该这样工作
    • 问题已解决,但存在问题,我使用相同的模型上传个人资料图像,当我正确显示路径时,相同的模型将获取图像路径,但当我上传时显示“取消链接(E :\\xampp\\htdocs\\feature-master\\public\\profile_images\/http:\/\/localhost\/feature-master\/public\/profile_images\/jwztUw4hbv.png): 没有这样的文件或目录"
    • 因为我在上传时删除了一次
    猜你喜欢
    • 2014-04-16
    • 2020-09-28
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多