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 >
<label for="">
<input type="checkbox" name="status" id="status">Status
</label>
</div>
CodePudding user response:
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
]);
}
CodePudding user response:
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.
CodePudding user response:
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 >
<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;
}