3

I have a project. At the moment, I am working with a CV (curriculum vitae) table. So, I was at the point that each CV can contain one or more Phone numbers and e-mails.

Because I already had around 7 tables associated with CV like skills, languages and so on, I decided to save emails and phones in the Сv s columns, as JSON columns.

So, in my migration I put

$table->json('phone');
$table->json('email');

How could I manipulate this

<input type="text" name="phone[]"> 
 <input type="text" name="email[]">

for storing this data from Controller in DB, and how should I retrieve them in view?

2
  • from my understanding you are creating TWO json fields in the database and gain nothing unfortunately. Commented Jan 22, 2018 at 15:49
  • I want to store 1 or multiple phone numbers in one column as JSON, an then in view to retrive that json and output JSON objects with foreach Commented Jan 22, 2018 at 15:52

1 Answer 1

2

Use attribute casting. In this case, you'll not need to convert the data from array to JSON and back.

From the docs:

The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model

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

4 Comments

Thanks for your answer. Can you provide some pseudo-code how it should look in Controller for saving, and outputing in Blade? Thanks!
@priMo-ex3m just work with the array as usual $model = new Model; $model->phone = $request->phone; $model->save();
So, if from front-end to back-end came array like ` $request->phone = [ 079111000, 069333555, 073666432 ] ; ` , $model->phone will save it automatically as JSON column, yep? But, when retrieving this $model->phone in Blade, how should I iterate through JSON objects in that case? Thanks.
@priMo-ex3m in the view you can iterate over the data as through an array.

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.