【发布时间】:2019-09-10 11:30:23
【问题描述】:
如何从 Laravel API 返回图像列表? 我想将 API 中的图像作为集合发送。我该怎么做? 如果可能的话,我想使用 ProductCollection 资源来做到这一点。 从现在开始谢谢你。
我想从中获取文件数据:
{
"data": [
{
"id": 20,
"name": "Cali Howe",
"price": "4.00",
"imageUrl": "C:\\Shop\\shop.api\\public\\img/default.png",
"category_name": "Consequuntur ut.",
"detail": "http://127.0.0.1:8000/api/product/20"
},
{
"id": 19,
"name": "Annie Murazik",
"price": "13.00",
"imageUrl": "C:\\Shop\\shop.api\\public\\img/default.png",
"category_name": "Consequuntur ut.",
"detail": "http://127.0.0.1:8000/api/product/19"
}
],
"links": {
"first": "http://127.0.0.1:8000/api/product?page=1",
"last": "http://127.0.0.1:8000/api/product?page=10",
"prev": null,
"next": "http://127.0.0.1:8000/api/product?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 10,
"path": "http://127.0.0.1:8000/api/product",
"per_page": 2,
"to": 2,
"total": 20
}
}
产品控制器:
public function index()
{
return ProductCollection::collection(Product::orderBy('id', 'DESC')->paginate(2));
}
产品系列:
class ProductCollection extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'imageUrl' => $this->imagePath('default.png'),
'category_name' => $this->category->name,
'detail' => route('product.show', $this->id),
];
}
}
产品型号:
class Product extends Model
{
protected $guarded = ['id', 'created_at', 'updated_at'];
public function category()
{
return $this->belongsTo(Category::class);
}
public function imagePath($fileName)
{
return public_path('img/' . $fileName);
}
}
产品迁移:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id');
$table->string('name')->index();
$table->decimal('price')->default(0);
$table->string('image')->nullable();
$table->timestamps();
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
});
}
【问题讨论】:
-
您预计会发生什么?当你运行你提供的代码时会发生什么?我还没有测试过它,但从它的外观来看,你通过使用资源收集走上了正确的轨道。试着更好地描述你的问题,并解释你的方法遇到了什么问题。