2

I have a four image field in my form for different use. When I try to upload images on two fields image_oneand 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?

4
  • Are you tested with same pictures? Could be a size problem. Commented May 2, 2018 at 7:18
  • @AliÖzen try with all possibilities. Commented May 2, 2018 at 7:29
  • * sometimes it upload image_one and sometimes only image_two* uh, as in, the field value is empty? could you post your form element on the resulting html? if its size issue, perhaps you will need to chunk your post request using multipart/form-data as enctype. Commented May 2, 2018 at 7:37
  • Using on POSTMAN Commented May 2, 2018 at 7:38

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.