Search code examples
phpimagelaraveleloquentintervention

Can not update image in laravel 5.1?


Any one can help me with this? I try to update new image for my project but, it get errors.If I don't choose new image just update content only it's ok, but with new image I cannot update. This is my code

public function updateStudent(UpdateStudentRequest $request){//(Request $request)
    $id = $request->input('id');
    $student = Students::find($id);

    if( $request->hasFile('pic') ){
    $path = 'images/';
    $file = Image::make(input::file('pic'));
    $fileName = Input::file('pic')->getClientOriginalName();
    $file->save($path."original/".$fileName);
    $students->original = $path."original/".$fileName;
    //get the desire image size
    $file->fit(120,90);
    $file->save($path."fit/".$fileName);
    $students->image = $path."fit/".$fileName; 
    }

    $student->first_name = $request->input('first_name');
    $student->last_name = $request->input('last_name');
    $student->email = $request->input('email');
    $student->password = $request->input('password');
    $student->address = $request->input('address');

    $student->save();
    }

This is the error:

ErrorException in Crud.php line 73:
Creating default object from empty value

Solution

  • It seems that your $student variable is empty. You get this error when you try to assign a value to an attribute of an object, but the object reference is null.

    In the future use Student::findOrFail($id) instead of Student::find($id), this way you'll make sure that if object could not be found you'll get an exception.