How can i avoid image required in edit form if image exist in laravel?

Viewed 1495

I am adding and editing a user with same function (Store), when ever i add a user it asks me image is required but whenever i edit a user which have image it also ask me image is required and i want if a image is already present it wont ask me , please see my above code i had recently changed my code according to Gurpal singh

In my controller
                                 

        public function rules()
{
                $child_details = Children::findOrFail($inputs['id']);
    $rules =  [
       'child_name' => 'required',
                   'gender' => 'required',
                   'dob' => 'required',
                   'current_class' => 'required',
                    'b_group' => 'required',
                    'm_tongue' => 'required', 
                    'image' => 'image',
         ];

    if ($child_details->notHavingImageInDb()){
        $rules['image'] = 'required|image';
    }
    return $rules;
 }
 
 public function Postchild(Request $request)
    {

            $data =  \Input::except(array('_token')) ;
             $validator = \Validator::make($data,$rules);
             $inputs = $request->all();
             if ($validator->fails())
            {
                    return redirect()->back()->withInput()->withErrors($validator->messages());
            }
          
              if(!empty($inputs['id'])){
                $child_details = Children::findOrFail($inputs['id']);
            }else{
                $child_details = new Children;
            }


           $child_details->parent_id = Auth::User()->id;
           $child_details->child_name = $inputs['child_name'];

           $child_image = $request->file('image');

        if($child_image){

            $tmpFilePath = 'uploads/childrens/';
             $extension =   $child_image->getClientOriginalExtension();
            $hardPath =  str_slug($inputs['child_name'], '-').'-'.md5(time());


            $img = Image::make($child_image);

            //$img->resize(180)->save($tmpFilePath.$hardPath.'-b.jpg');
            $img->fit(250, 250)->save($tmpFilePath.$hardPath.'.'.$extension);

            $child_details->image = $hardPath.'.'.$extension;

        }
         
            $child_details->save();

       
  if(!empty($inputs['id'])){


                return \Redirect()->route('child_list')->with('success', 'Child has been updated');


        }else{

                return \Redirect()->route('child_list')->with('success', 'Child has been added');


        }    

    }

5 Answers

You can use Conditionally Adding Rules Not having image in database

Add this in model

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

This is the validation rule request

public function rules()
{
    $user = User::find(Auth::id());
    $rules =  [
       'name' =>'required|max:100',
        'image' =>'image',
         ];

    if ($user->notHavingImageInDb()){
        $rules['image'] = 'required|image';
    }
    return $rules;
 }

Don't forgot to import auth and user model ie

 use App\User;
 use Auth;

for more detail click here

You can normally do like below :

$rule = array(
    'name' => 'required',
   );

if (!empty($inputs['id'])) {
    $user = User::findOrFail($inputs['id']);
} else {
    $rule["image"] = "required";
    $user = new User;

}

It is better to separate them or simply create another function. But you can put an if statement that if the image is in the request or not.

Like this:

    if(! isset($data['image'])){ //if the image is not in the request

          //Your code          

    }
    else{ //if the image is in the request

         //Your code

    }

If you want a code for storing, renaming, moving an image feel free to request.

You can use validation's after hook.

public function Postchild(Request $request)
{

   //Define your rules
   $rules =  [
           'child_name' => 'required',
           'gender' => 'required',
           'dob' => 'required',
           'current_class' => 'required',
           'b_group' => 'required',
           'm_tongue' => 'required', 
         ];

  //Validate your data       
  $data = $request->except('_token');
  $validator = \Validator::make($data,$rules);


  $validator->after(function ($validator) {

    //Check the mode of request (Create or Update)
    if(!empty($data['id'])){
        $child_details = Children::findOrFail($data['id']);
        if($child_details->image == null){
          $validator->errors()->add('image', 'Image field is required');
        }
    }
  });
  if ($validator->fails()) {
  return redirect()->back()
  ->withErrors($validator)
  ->withInput();
  }
}

Just this few lines can solve your problems... You have to check there image have or not.

Rules in a private or protected function

  private function validateRequest($request)
     {
        //This is for Update without required image, this will check that In DB image have or not

        $child_image = Children::find($request->id);
        $rules = [];
        if ($child_image) :
          if ($child_image->image == null):
             $rules['image'] = 'required|image|max:1999';
          endif;



        //This is for regular validation
        else :
          $rules = [
              'image' => 'required|image|max:1999',
           ];
       endif;
         return $rules;
}
Related