4

I have a form attributes called, name, description and features where features is a multiple checkboxes which is like

feature 1
feature 2
feature 2
feature 4

User can select multiple checkbox at once. I have a database table called product like

-----------------------------------------
    id    name    description    features  
-----------------------------------------

When user selects the multiple checkbox, i need to insert all checkbox value in the features column. Right now I can echo the selected checkbox value like

 $feat = Input::get('features');
    foreach ($feat as $key => $n){
     echo $feat[$n];
    }

but I need those features to insert into the database, for normal insertion, we would do like:

$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->features = Input::get('features');
$product->save();

but how should i modify the above code in order to save the array value to the database? I am trying to insert the value to same column because i won't be querying it on the basis of features.

1
  • Saving the array value to the database in a single column is a very bad idea. You should consider normalising your data and data structure first. Use something like a product_feature table, where, for each product you will have several rows, one for each feature. Commented Sep 8, 2015 at 9:29

5 Answers 5

6

It's quite simple. If you know that you won't query the features, it's perfectly fine to store them as Json or a serialized array. But if you will need to query them and they are a key aspect of your application, you should put them in their own table.

I prefer to store arrays in Json-format because it's easier to read and is not specific to PHP. Laravel gives you pretty sweet options to make this work.

At first, declare the features-field of you products-table as json in your migration:

Schema::create('products', function (Blueprint $table) {
    // ...
    $table->json('features');
});

Then tell your Product-model to automatically cast it to an array when you access it by simply setting a $casts-attribute:

class Product extends Model
{
    // ...
    protected $casts = [
        'features' => 'json'
    ];
}

That's it. Now the array will be stored as Json, but when you access it with $product->features you'll get an array back.

To make everything even more simple, you should set up a fillable attribute on your Product model:

class Product extends Model
{
    // ...
    protected $fillable = ['name', 'description', 'features'];
}

This allows for doing something like this in your controller (or wherever you create the product):

$product = Product::create(Input::all());

...instead of newing it up and setting the attributes one by one.

And as mentioned above, be sure you don't need the features to be query-able, meaning you won't encounter situation where you're trying to get certain products only having specific features or something. But if you do need to look up features, you should put them in their own table. Otherwise this approach is just fine because it's more convenient.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm confused that someone said 'features' => 'json', not 'features' => 'array'. Official laravel doc says (even the link in this answer) 'array' is correct but some people including this answer say 'json'. What is correct? Both?
Hey @Arbitrary, both work and can be use synonymously, whatever fits your mental model ("cast this to an array" vs. "parse this json data")
2

Please look to database normalization for information how to store Data which is in a 1:N relationship. You have to create an extra table like "product_feature" with the attributes: ['id', 'product_id', 'function_name'].

Then your Insert function looks like this:

$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->save();

$feat = Input::get('features');

foreach ($feat as $key => $n){
    $product_function = new ProductFunction;
    $product_function->product_id = $product->id;
    $product_function->function_name = $feat[$n];
    $product_function->save();
}

Hope it helps!

1 Comment

Hey @linx Your approach is right but in foreach loop instead of $feat[$n] must set $feat[$key] it is work correctly thanks.
1

You could use the json_encode function to save the array as a json string.

$product->features = json_encode(Input::get('features'));

But I will also agree with @AdrianBR it is a bad idea to saving the array value to the database in a single column.

Comments

0

I had something similar to this although i used ajax to send the values

<div class="row mb-3" id="insert_new_item">
<div class="col-lg-6">
<p>Item Description</p>
<input value="" type="text" name="order[description]"  class="form-control product " id="" placeholder="Your Item Description">
</div>
<div class="col-lg-1 col-sm-6 col-12 mt-lg-0 mt-3">
    <p>Qty</p>
    <input placeholder="0" type="text" name="order[quantity]"  min="1" class="text-right form-control qty" id="" min="1">
</div>
<div class="col-lg-2 col-sm-6 col-12 mt-lg-0 mt-3">
    <p>Rate/Unit (&#8358; )</p>
    <input placeholder="0.00" type="text" name="order[rate]" class="text-right form-control rate" id="">
</div>
<div class="col-lg-2 mt-lg-0 mt-3">
    <p>Amount (&#8358; )</p>
    <input  type="text" name="order[amount]" id="" class="text-right form-control amount" readonly value="0" >
</div>
<div class="col-lg-1">
    <span><i class="fa fa-times text-danger  removeItem" style="font-size: 22px"></i></span>
</div>

So when i console.log(any value) i get this:

["0" : "value 1", "1" : "value 2"]

from my controller i can do this

foreach ($request->description as $key => $description) {
    $order = Order::create([
        'description' => $description,
        'amount' => $request->rate[$key],
        'quantity' => $request->quantity[$key],
        'invoice_id' => 7
     ]);

}

Comments

0

You can insert like this,

$candidate_data = array(

            'mobile' => $request->get('mobile'),
            'password' => $request->get('password')
    );

DB::('tablename')->insert($candidate_data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.