PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to get checkbox value in a Laravel controller?

 November 15, 2022     laravel, laravel-6     No comments   

Issue

I have a checkbox in my form and I want to save its value into the database. When I check it, its value will be 1 and when I uncheck it then it's value will be 0. However, in the controller, I am getting NULL all the time. But why? Is it possible to solve without jQuery?

Blade/View

<form action="{{ route('admin.categories.store') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group>
       <label>
          <input type="checkbox" name="category_is_menu"
                 value="{{ old('category_is_menu', isset($category) ? 'checked' : '') }}"/>
       </label>
    </div>
    <input class="btn btn-success" type="submit" value="Submit">
</form>

Controller

public function store(Request $request)
{
    $category = new Category();
    $category->category_is_menu = $request->category_is_menu;

    return $category;
}

Unfortunately, it's giving me NULL for category_is_menu.


Solution

Either use the hidden input trick as mentioned in the other answers or just check if the input was passed at all. If it was passed at all it was checked, if its not there it was not checked:

$category->category_is_menu = $request->has('category_is_menu');

If it was checked you get true, 1, if it wasn't checked you get false, 0.



Answered By - lagbox
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing