Laravel - Store multiple checkbox form values in database
When you use checkboxes in a Blade view, the browser sends an array of selected values to your server, not a single string. However, if your model defines services as a standard fillable string field in the database, Laravel will attempt to cast that array into a single value. In many cases, this results in only the last selected item being stored or the entire array being converted to a string representation like "1,2,3" depending on how you handle it.
In the specific scenario where your database column expects an integer but receives an array, Laravel's default behavior often leads to data loss. If you inspect the request payload in your controller using dd($request->all()), you will see that services is indeed a collection of integers (e.g., [1, 3, 5]). When you pass Request::all() directly to orders::create(), Laravel tries to map these values to the fillable properties. If the underlying database column for services is defined as an integer or string and not explicitly designed to hold a serialized list, the mapping fails silently or truncates the data.
To resolve this, you must handle the aggregation of multiple checkbox selections before persisting them to the database. The most robust approach depends on your data requirements and the structure of your orders table.
Option 1: Serialize into a Single String Column
If your database schema already defines the services column as a string or text field (e.g., VARCHAR), you can manually convert the array into a delimited string. This is often the quickest fix for existing schemas, though it requires careful handling when retrieving and splitting the data later.
In your controller, access the request input specifically to ensure you are getting an array, then join the values:
public function store(Request $request)
{
$services = $request->input('services', []);
// Join the array with a delimiter (e.g., comma or pipe)
if (!empty($services)) {
$servicesString = implode(',', $services);
// Create the order with the serialized string
Order::create([
'category' => $request->input('category'),
'services' => $servicesString,
'total_price' => $request->input('total_price'),
'user_id' => $request->user()->id,
'status' => 'pending',
]);
} else {
// Handle the case where no checkboxes were selected
Order::create([
'category' => $request->input('category'),
'services' => null, // Or an empty string depending on DB constraints
'total_price' => $request->input('total_price'),
'user_id' => $request->user()->id,
'status' => 'pending',
]);
}
return response()->json(['message' => 'Order created successfully']);
}
Ensure your Model's $fillable property includes services, and that your migration defines the column as a string type:
// Migration example
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->string('services')->nullable(); // Stores "1,3,5"
$table->decimal('total_price', 10, 2);
$table->foreignId('user_id');
$table->enum('status', ['pending', 'completed']);
});
Option 2: Use a JSON Column (Recommended)
For modern Laravel applications, storing arrays in a JSON column is the preferred method. This allows you to store multiple values without string parsing logic and maintains type safety within the application layer.
Update your migration to use the json type for the services column:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->json('services')->nullable(); // Stores [1, 3, 5] as native JSON
$table->decimal('total_price', 10, 2);
$table->foreignId('user_id');
$table->enum('status', ['pending', 'completed']);
});
Your controller logic remains almost identical because Laravel handles the conversion between arrays and JSON automatically when using Eloquent. You can simply pass the array directly:
public function store(Request $request)
{
Order::create([
'category' => $request->input('category'),
'services' => $request->input('services', []), // Passes [1, 3, 5] directly
'total_price' => $request->input('total_price'),
'user_id' => $request->user()->id,
'status' => 'pending',
]);
return redirect('/success-page');
}
When retrieving the data later, Eloquent will automatically cast the services attribute back into a PHP array. If you need to query for specific services, you can use the whereJsonContains method available in Laravel 5.6+ or the contains helper on JSON columns.
Handling the View and Logic Separation
Finally, ensure your view logic correctly handles the submission. The provided Blade snippet uses name="services" without a prefix, which is correct for creating a top-level array. However, always validate the request in your controller to prevent type errors if the form is submitted with empty checkboxes. Using $request->input('services', []) ensures you always receive an array, preventing unexpected null casts that could break your application logic.
For more complex scenarios involving multi-dimensional arrays or specific validation rules for checkbox groups, consider utilizing Laravel's validate method in the controller to enforce strict input requirements before creating the record.