Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

f.alabakhsh@gmail.com's avatar

Passing a boolean value from checkbox in Laravel form

I am trying to save boolean value when I create a new Product and then have it update the value if I update the Product.

schema

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();

            $table->boolean('featured')->default(false);

        });
    }

product model

 protected $casts = [
        'stock-status' => ProductStatusEnum::class,
        'featured' => 'boolean',

    ];

ProductController.php

 public function store(Request $request)
    {
        $request->validate([
           'featured' => $request->has('featured');
        ]);
        $request->Product::all();
        return redirect()->route('Product.index')->with( 'محصول با موفقیت ثبت شد');
    }

create blade

<form method="post" action="{{ route('product.store') }}" enctype="multipart/form-data" >
                @csrf
<label for="featured" class="inline-flex relative items-center cursor-pointer">
  <input type="checkbox" name="featured" class="switch-input sr-only peer" value="1" {{ old('featured') ? 'checked="checked"' : '' }}/>
<button type="submit">
     Create
</button>
</label>

</form>

I GET this ERORR

TypeError PHP 8.1.6 9.52.4 array_key_first(): Argument #1 ($array) must be of type array, bool given

0 likes
2 replies
LaryAI's avatar
Level 58

The issue is with the validation in the store method of the ProductController. The validate method expects an array of validation rules, but in this case, a boolean value is being passed instead. To fix this, update the validation rule to be an array with the featured field and its validation rule:

public function store(Request $request)
{
    $request->validate([
        'featured' => ['boolean']
    ]);

    // rest of the code
}

Also, in the create blade file, the button tag should be outside the label tag. Here's the updated code:

<form method="post" action="{{ route('product.store') }}" enctype="multipart/form-data">
    @csrf
    <label for="featured" class="inline-flex relative items-center cursor-pointer">
        <input type="checkbox" name="featured" class="switch-input sr-only peer" value="1" {{ old('featured') ? 'checked="checked"' : '' }}/>
        <span class="peer-toggle peer-success"></span>
        <span class="peer-label">Featured</span>
    </label>
    <button type="submit">Create</button>
</form>
Snapey's avatar

you have lots of errors

Firstly, forget validation for a checkbox

second, what product do you want to update?

third, get the product, set the checkbox and save it

Finally, DONT JUST SAY YOU GOT THIS ERROR. Note the file it occurred in and the line number

Please or to participate in this conversation.