Reputation: 857
I have a four image field in my form for different use. When I try to upload images on two fields image_one
and image_two
sometimes it uploads image_one
and sometimes only image_two
My controller code:
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();
}
}
And my storePostPicture
function in model :
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;
}
What am I doing wrong?
Upvotes: 2
Views: 437
Reputation: 2775
In your migration table, make sure you have made all the image fields nullable:
$table->string('image_one')->nullable();
$table->string('image_two')->nullable();
...
Also, save your post model after collecting all the data.
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
Upvotes: 2