我有一个nuxtJs前端,它将请求发送到laravel API,用户可以在他们的帖子中上传图像。这是通过laravel spatie medialibrary包上传的。
现在,当用户详细查看他们的帖子时,他们上传的图像也应该会显示出来。
NuxtJS向接口发出fetch请求:
async fetch() {
this.post = await this.$axios.$get('http://127.0.0.1:8000/api/posts/' + this.$route.params.slug)
},请求在show方法上输入
public function show(string $slug): PostCollection
{
return new PostCollection(Post::with(['comments', 'media'])->where('slug', '=', $slug)->get());
}这将返回一个新的ResourceCollection
#[ArrayShape(['data' => Collection::class])] public function toArray($request): array
{
return [
'data' => $this->collection,
];
}包含这类数据
{
"data": [
{
"id": 1,
"title": "My first blog post",
"slug": "my-first-blog-post",
"content": "Beep boop",
"deleted_at": null,
"created_at": "2021-07-05T08:43:00.000000Z",
"updated_at": "2021-07-05T08:43:00.000000Z",
"comments": [],
"media": [
{
"id": 1,
"model_type": "App\\Models\\Post",
"model_id": 1,
"uuid": "3c899a67-d59a-41b7-b5ae-f88e9bfc901b",
"collection_name": "images",
"name": "index",
"file_name": "index.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"conversions_disk": "public",
"size": 11803,
"manipulations": [],
"custom_properties": [],
"generated_conversions": [],
"responsive_images": [],
"order_column": 1,
"created_at": "2021-07-05T08:43:00.000000Z",
"updated_at": "2021-07-05T08:43:00.000000Z"
}
]
}
]
}现在我该如何让它在JSON响应中返回图像的完整路径,比如http://127.0.0.1:8000/public/storage/1/filename.jpg,这样我就可以在我的前端显示它了。
Post模型如下所示:
<?php
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use JetBrains\PhpStorm\ArrayShape;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Post extends Model implements HasMedia
{
use HasFactory;
use SoftDeletes;
use Sluggable;
use InteractsWithMedia;
protected $fillable = [
'title',
'slug',
'content',
'image'
];
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
#[ArrayShape(['slug' => "string[]"])] public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
}发布于 2021-07-06 07:42:32
该包返回media()关系的Media对象的集合。在每个对象上,都可以调用函数->getFullUrl()。
为了返回带有完整Attribute的媒体,您必须创建自定义URL。
你可以把类似这样的东西添加到你的模型中,或者添加到一个特征中,如果你需要重用这个(未测试的):
public function getFullUrlMediaAttribute()
{
return $this->getMedia()->map( function($mediaObject) {
$mediaObject->full_url = $mediaObject->getFullUrl();
return $mediaObject;
});
}有关更多信息,请查看Laravel Medialibrary docs。
这样做之后,您必须将show函数更新为:
public function show(string $slug): PostCollection
{
return new PostCollection(Post::with(['comments'])
->where('slug', '=', $slug)
->get()
->append('full_url_media')
);
}https://stackoverflow.com/questions/68254563
复制相似问题