【问题标题】:Return image path in Laravel API resource返回 Laravel API 资源中的图像路径
【发布时间】:2019-11-24 01:40:46
【问题描述】:

我正在构建一个仅 laravel 5.8 API 的应用程序,并希望将图像路径作为 API 资源的路径返回,以便可以在图像源属性中使用它。所以这就是我必须做的来实现这一点。 1.我运行php artisan storgae:link命令创建从public/storagestorage/app/public的符号链接

  1. 首先,当像这样成功创建新产品时,我将图像存储在 productImages 表中
public function store(Request $request)
{
    // create & store the product
    if ($product = Product::create([
        'name'      => $request->name,
        'category'  => $request->category,
        'status'    => $request->status,
        'price'     => $request->price,
        'interest'  => $request->interest,
    ])) {
        // store the product image
        $file = $request->file('image');
        $destinationPath = "public/images/products";
        $filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();

        Storage::putFileAs($destinationPath, $file, $filename);

        ProductImage::create([
            'product_id'    => $product->id,
            'name'          => $filename
        ]);
    }

    // return new product
    return new ProductResource($product);
}
  1. 像这样返回 ProductResource 中的图片路径
public function toArray($request)
{
    return [
        'id'        => $this->id,
        'name'      => $this->name,
        'category'  => $this->category,
        'status'    => $this->status,
        'price'     => $this->price,
        'interest'  => $this->interest,
        'hidden'    => $this->hidden,
        'imageUrl'  => asset('images/products/' . $this->image->name)
    ];
}

在我的本地服务器上测试它,我得到了这样的路径

{
    "id": 1,
    "name": "dpk",
    "category": "fuel",
    "status": "open",
    "price": 100000,
    "interest": 0.2,
    "hidden": 0,
    "imageUrl": "http://localhost:8000/images/products/pramopro_dpk_1.jpeg"
  }

当我尝试通过在浏览器中输入http://localhost:8000/images/products/randomtext_1.jpeg 来查看图像时,我收到404 not found 错误。

但是这个http://localhost:8000/storage/images/products/pramopro_dpk_1.jpeg 按预期显示图像。

我应该如何检索图像路径以使其正常工作?

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    asset() 函数把你放在你的公共目录中,你需要将 /storage 添加到你的文件路径中,在你的 toArray 函数中试试这个

    'imageUrl'  => asset('storage/images/products/' . $this->image->name)
    

    个人笔记,在 laravel 中处理媒体可能会很头疼我个人使用 spaite 的 LaravelMediaLibrary

    https://github.com/spatie/laravel-medialibrary

    它真的帮助了我,让处理媒体变得尽可能简单,尤其是在处理同一模型的多个媒体时

    【讨论】:

    • 我会检查LaravelMediaLibrary 包。我实际上必须将storage 添加到路径中。
    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多