使用图像的 Laravel 8 中的访问器获取 table 值

Fetch table value using Accessor In Laravel 8 for image

我的模型名称是 'data',字段名称是 'image'。

在模型中,当我尝试获取图像的 URL 时,它显示此错误 Undefined property: App\Models\Data::$image 使用 $this->image;

但是当我尝试使用 $this->name 获取名称时它工作正常。

为了更好理解,我还附上了DB的截图。

注:我在模型中添加了use Storage;

请帮我解决问题。

控制器

型号

在laravel中开始学习查询之前,先整理一下代码并将其调整为标准语法,以免给自己造成困难。

接受变量中的模型数据

例如我得到最新的行

$mydata = \App\Models\Data::orderBy('id','DESC')->first();

如果你想获取你的数据,你可以这样做

$mydata->name;
$mydata->image;

如果仍然无法正常工作,请添加您的模型的屏幕截图。

[评论回答]

public function getImageAttribute ($id) {
     return Data::where('id',$id)->first()->image;
}

我得到答案参考 https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

public function getImageAttribute($image)
{
    $Img_Url = $image;
    return $ImgUrl;
}