【发布时间】:2021-06-30 10:52:35
【问题描述】:
我正在使用 laravel 8 构建一个 API,并且我有具有多态关系的帖子和图像表(因为我有用户并且我也使用图像)
所以我想上传多张图片并在邮递员中完成,所以当我上传图片并输入带有值的帖子字段时,如下所示:
如您所见,我的 foreach($files as $file) 中有错误
ErrorException: Invalid argument supplied for foreach()
(在标题部分我输入带有 multipart/form-data 值的 Content-Type)
所以我认为我的问题在于 postController 中的 store() 方法,
我的代码:
张贴表:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->longText('body');
$table->string('video')->nullable();
$table->string('study_time');
$table->integer('likes')->nullable();
$table->tinyInteger('status')->nullable()->comment('status is 1 when a post is active and it is 0 otherwise.')->nullable();
$table->text('tags')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('user_id')->references('id')->on('users');
});
还有我的图片表:
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('imageable_id');
$table->string('imageable_type');
$table->string('url');
$table->timestamps();
});
和后期模型:
.
.
.
.
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
还有我的图像模型:
protected $fillable = [
'url'
];
public function imageable(){
return $this->morphTo();
}
还有我在 postController 中的 store() 方法:
public function store(Request $request )
{
$post = new Post;
$post->category_id = $request->get('category_id');
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->study_time = $request->get('study_time');
$post->tags = $request->get('tags');
$post->user_id = JWTAuth::user()->id;
$tags = explode(",", $request->tags);
$post->tag($tags);
$allowedfileExtension=['pdf','jpg','png'];
$files = $request->file('fileName');
foreach ($files as $file) {
$extension = $file->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if($check) {
foreach($request->fileName as $mediaFiles) {
$url = $mediaFiles->store('public/images');
//store image file into directory and db
$image = new Image();
$image->url = $url;
}
}
else {
return response()->json(['invalid_file_format'], 422);
}
}
$post->image()->save($image);
$post->save();
return response()->json($post , 201);
}
感谢您的帮助:}
【问题讨论】:
标签: php laravel api polymorphism