Search code examples
phpvalidationlaravellaravel-5laravel-validation

Image validation in Edit form in laravel 5.2


I have a issue, Please take a look below.

I have a edit user profile section where we update user account, i want to check if no image exists in table & user too not provided image then we have to validate the image & show an error. if there is already a image exists in table then no image validation suppose to check. Everything works good except image validation.

i am using from request for validation. below is my validation rules in request file.

public function rules()
{
    return [
        'user_type' =>'required',
        'first_name' =>'required|max:100',
        'last_name' =>'required|max:100',
        'email' =>'required|email|max:100',
        'image' =>'required|image',
        'zip_code' =>'required|numeric|min:5',
    ];
}

I am using Laravel 5.2, Thanks in advance.


Solution

  • Finally i figure out the solution using help of @Amir. below is the complete solutions of this issue.

    //add this in user model

    public function notHavingImageInDb(){
        return (empty($this->image))?true:false;
        //return true;
    }
    

    //import the User model & Auth class in request class.

    use App\User;
    use Auth;
    

    //add this in from request

    public function rules()
        {
            $user = User::find(Auth::id());
    
            $rules =  [
                'user_type' =>'required',
                'first_name' =>'required|max:100',
                'last_name' =>'required|max:100',
                'email' =>'required|email|max:100',
                'image' =>'image',
                'zip_code' =>'required|numeric|min:5',
            ];
    
            if ($user->notHavingImageInDb()){
                $rules['image'] = 'required|image';
            }
    
            return $rules;
        }
    

    Now all done.

    In the above code we check if the column has some value or not in validation, if yes then model function return true, this make the if condition active in request class, else, if condition remain inactive. works like charm.

    Thanks