skip to Main Content

Hello, I have an adminController as below. Even though I checked the status box, it comes to the database as zero. I can’t figure out why if/else block doesn’t work. If I use debug i can see "on" value for checkbox

public function addPost(Request $request){

    $name=$request->title;
    $content=$request->content;
    $status=$request->status;

    if(!is_null($status)){
        $status=0;
    }
    else{
        $status=1;
    }

    Posts::create([
        'name' =>$name,
        'content' =>$content,
        'status' =>$status
    ]);
}

addPost.php (it’s my form)

<div class="form-group">
    <label for="">
        <input type="checkbox" name="status" id="status">Status
    </label>
</div>

form image
mysql

3

Answers


  1. This may help you a little bit change:

    public function addPost(Request $request){
    
        $name=$request->title;
        $content=$request->content;
       
    
        //if box is checked status will be 1
        if($request->status){
            $status=1;
        }
        //if box is unchecked status will be 0
        else{
            $status=0;
        }
    
        Posts::create([
            'name' =>$name,
            'content' =>$content,
            'status' =>$status
        ]);
    }
    
    Login or Signup to reply.
  2. First problem is if(!is_null($status)) it is never null because
    you can write in your migration default(0) so here we can manage with
    Controller.

      if($status == 0)
       {
         $status=1;
       }
    

    here status is default 0 so we check $status == 0 then we have to change it to 1 and if this condition is false then status value is already 1.

    Login or Signup to reply.
  3. As I can see you are checking the !is_null on the code, because of which you are getting the 0 if you are checking the checkbox, the condition should be like this:

    if(is_null($status)){
         $status=0;
    }
    else{
         $status=1;
    }
    

    if you are still confused about this then pass a value from the checkbox and check that value in the controller:

    <div class="form-group">
        <label for="">
            <input type="checkbox" name="status" id="status" value="1">Status
        </label>
    </div>
    

    Now, you can check like this in the controller:

    if(isset($status) && $status == 1){
             $status=1;
        }
        else{
             $status=0;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search