1

I am wondering what the best way to accomplish this would be. I need to store an array such as:

['hello', 'world', 'love']

Inside one column in a table. I do not want to create a new table where each value in the array becomes a separate row. Is there a better way? I guess my biggest concern is performance.

So when creating the migration for this column, ideally I would insert an array with 3 default/nullable values. Then I can set actual values for the array when needed in my application.

Simple scenario: I have a table called desk and I want to store 3 items that are on top of the desk such as ['pencil', 'ruler', 'stapler'], but I do not want to create a separate table desk_items to have a row for each item. Hope this makes sense.

Using Laravel and MYSQL

Thank you.

4
  • 4
    I'm not going to do all the work for you, but I will suggest you look at the following : 1. Storing arrays in a database as JSON. 2. Laravel's "casting" of attributes. Commented Oct 9, 2021 at 17:42
  • 1
    Sidenote. If your concern is performance then keep in mind that queries to find a row which has a specific element in that array will be much slower than if you had them as rows in a related table Commented Oct 9, 2021 at 22:07
  • Yea been reading up, hasMany relationship is probably the best way? Commented Oct 9, 2021 at 22:07
  • 1
    it depends on your use case but yes for a simple association of a row with a set of values that are specific to that row a hasMany relationship is the best way to go. Commented Oct 10, 2021 at 19:55

2 Answers 2

6

make desc table as jsonb format

$table->jsonb('desk');

and in model use casts

protected $casts = [
    'desk' => 'array',
];
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to store the array in Database table you should send it with json_encode .

$data = new Data; 
$data->Name = json_encode($request->DataName);
$data->save();

Thus, you can store an array in the name column of your data table. to use this data you need to call the data with json_decode.

 $data = json_decode(Data::find(1)->Name);

1 Comment

@Etra This is not the best option for Laravel. You will always have to do json_decode wherever you output this data

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.