我的表单中有四个图像字段供不同用途使用。当我尝试在两个字段image_one
和image_two
上传图片时,有时会上传image_one
,有时仅上传image_two
我的控制器代码:
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
$post->save();
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
$post->save();
}
}
我的storePostPicture
函数在模型中:
public function storePostPicture($image) {
if($image instanceof \Illuminate\Http\UploadedFile && $image->isValid() && $image->isReadable()) {
$filePath = 'public/images/user' . DIRECTORY_SEPARATOR . 'post';
if(!File::exists(storage_path('app' . DIRECTORY_SEPARATOR . $filePath))) {
File::makeDirectory(storage_path('app' . DIRECTORY_SEPARATOR . $filePath), 0755, true);
}
$imageName = sha1(time().time()) . ".". $image->getClientOriginalExtension();
if($image->storeAs($filePath, $imageName) !== false) {
$path = "/storage/images/user/post/";
return $path . DIRECTORY_SEPARATOR . $imageName;
}
}
return false;
}
我做错了什么?
答案 0 :(得分:2)
在您的迁移表中,请确保您已将所有图片字段设为可空:
$table->string('image_one')->nullable();
$table->string('image_two')->nullable();
...
此外,在收集完所有数据后保存您的帖子模型。
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
}
}
$post->save(); //saving the post model here