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

david001's avatar

json encode and append to current form submission request

I am using laravel. I have a form with many input fields such as first name,lastname,address etc.

I want to store address data in json format since address can have address 1,adderss2,city etc so I want to store as json

public function store(Request $request)
{
   $data = $request->all();
   dd($data);

}

it gives following result on dd($data);

array:5 [▼
  "_token" => "GEBkMtY6Plwt7OMYCH41QRh7S29XdgEniExNm4z6"
  "field_855" => "john"
  "field_856" => "doe"
  "fields" => array:2 [▼
    "field_857" => array:6 [▼
      "add1" => "Avenida Eva Perón"
      "add" => "aa"
      "c" => "CJN"
      "state" => "NW"
      "p" => "23"
      "country" => "CDE"
    ]
    "field_858" => array:6 [▼
      "addressone" => "PO Box 23"
      "address2" => "dd"
      "city" => "NEWCASTLE UNIVERSITY"
      "state" => "NSW"
      "postcode" => "223"
      "country" => "ABC"
    ]
  ]
]

I want to convert the data of $request->fields into json as "field_857"=>[{'add1':aAvenida Eva Perón',add:'aa',c:'CJN','state':'NWW','postcode':'233','country':'ABC'}] same for field field_858 as well.

so final array I want is like this:

dd($data);


array:9 [▼
  "_token" => "GEBkMtY6Plwt7OMYCH41QRh7S29XdgEniExNm4z6"
  "form_secret_token" => "T5yb8UZqIh8znSKbgTI32kNaAjsKlk4G"
  "itoken" => "Ju4qFduCNk"
  "field_855" => "john"
  "field_856" => "doe"
  "address" => "PO Box 23, NEWCASTLE UNIVERSITY NSW 2308"
  "fields" => array:2 [▶]
  "field_857" => "[{'add1':aAvenida Eva Perón',add:'aa',c:'CJN','state':'NWW','postcode':'233','country':'ABC'}]`"
  "field_858" => "[{'addressone':PO Box 23',address2:'dd',city:'NEWCASTLE UNIVERSITY','state':'NWW','postcode':'233','country':'ABC'}]`
]

I used array_keys() and array_values() to get keys and values of $request->field and assign to $data, I got error:illegal offset type

0 likes
10 replies
david001's avatar

@SilenceBringer thanks for reply. I made this in model:

   protected $casts = [
        'fields' => 'array',
    ];

but i still get same result on dd($request->all());

  "field_855" => "Sunt et quaerat esse"
  "field_856" => "Dolorem excepteur of"
  "fields" => array:2 [▼
    "field_857" => array:6 [▶]
    "field_858" => array:6 [▶]

This controller was previously written by someone which saves data if the response has field_suffix followed by id, for example field_855 and field_856 are saved in db since they are in field_id format. so I want to make similar format for fields array

  "field_855" => "Sunt et quaerat esse"
  "field_856" => "Dolorem excepteur of"
filed_857=>[{store as json}],
field_858=>[{store as json}]
martinbean's avatar

I want to store address data in json format since address can have address 1,adderss2,city etc so I want to store as json

@david001 And? Why does that mean you need to store it as JSON? It would be better to use a relational database to store data relationally and actually define an addresses table. You can take cues from the Schema.org project and standardise addresses using the following columns:

  • street_address
  • locality (the town or city)
  • region (county, state, province, etc)
  • postal_code
  • country

If you just want to smash everything into JSON, then store it in a noSQL database, or on disk. Because it’ll be about much use and as easy to query stored there than in a relational database like MySQL.

1 like
Tray2's avatar

@martinbean I agree.

Json columns are in my opinion a bad practice and should be used sparingly. You might think you save a bit of typing in your migration but you will type way more in your controllers and models. Definately not worth the hassle.

1 like
jlrdw's avatar

@david001 I agree, I would say experiment first and do the json first, and then edit it. Let;s say a user is updating their address or whatever.

Then experiment again with relational tables and see how much easier it is to edit data.

Then pick the best choice. I would never store large amounts of data like that as json.

I would store like @martinbean and @tray2 recommended.

1 like
Tray2's avatar

@jlrdw I agree. I would use it only temporarily if you get lots of data from an api and then to save time process it with a job and then store it in a regular table. This is a pretty good way to keep track of what has been received and for debugging purposes.

david001's avatar

@silencebringer @martinbean @tray2 @jlrdw Thanks for suggestion. The project I am working has table named responses within it we have field_id and answers field name where we store all the responses submitted from the form. lets say firstname john and lastname doe was submitted from the form. it is store as below in table

field_id   answers
12					john
13					Doe

12 and 13 are the field id of firstname and lastname. so when i have to show the data in view page I easily know john is the firstname and doe is the lastname with the help of field_id and display it as

firsname:john
lastname:Doe

Similarly, for addressfield i have its field id 18. and address field can have multiple field such as country,address1,address2,city.state so if i store in the same way that i stored firstname and lastname I would have date in following format

field_id answer
18            UK
18           Newcastle
18        3030

so how do i know uk is country, Newcastle is city and 3030 is postcode. is there anyway? so I am planning to store as json

{'country':uk,city:'New castle','state':3030}

Tray2's avatar
Tray2
Best Answer
Level 73

@david001 You are obviously not listening to us at all.

It a table you have field names

  • id
  • last_name
  • first_name
  • country
  • city
  • state

and so on.

When the request is submitted from you form you have names on those form inputs

<form action="/users" method="post">
  <input type="text" name="first_name">
  <input type="text" name="last_name">
<!-- and so on -->	
</form>

So in your controller you just validate preferably using a form request class

It could look something like this

class UserFormRequest extends FormRequest
{
    public function rules()
    {
        $rules = [
            'last_name' => 'required',
            'first_name' => 'required',
			'country' => 'required'
			//and so on
        ];

        return $rules;
    }
}

The your store method would look something like

public function store(UserFormRequest $request)
    {
       $user =  User::create($request->validated());
        return redirect(route('users.index'))->withStatus($user->name . ' successfully added.');
    }

All form fields in the html and all the fields in the table should have proper names not just field_20. If you store the date of birth of the user it should be named date_of_birth or maybe dob since it's a pretty standard acronym.

If you think that you have too many fields then you can alway break some of the fields into another table.

While using json might appear as a quick solution now, it surely will not be quick in the long run.

It will also affect the performance of the database since you can't really index a json column.

Let just say that you want to get a list of all the users that have their birthday between two dates.

This is pretty easy to do with a regular field and if you have thousands of users it will slow down and to speed it back up again you add an index one the date of birth field.

To do something similar for a json column you need to use stored generated columns which I don't think is supported by laravel's migration.

https://stackoverflow.com/questions/38389075/how-to-create-index-on-json-column-in-mysql

So basically you still need to create every single field anyway in your migration or at least the ones you need to index.

This is my last attempt to make you understand that json columns might seem like a simple and good solution but it's generally not a good one or a simple one. There are no shortcuts to a good database design and that a bad decision now will affect your application in for a long time. It's much better to make a good design now that scales well and can be made more performant in more ways than just throwing money at the problem. You also need to think a bit about the future. I a year new demands or needs has been requested from the users and you need to extract/add/remove/modify some part of the application.

Let's just say that the fields 857 and 858 are getting so big that your json field your application gets so slow when you try to do any type of crud and you need to extract it to it's own table for performance. Then you have your work cut out for you and you will curse yourself for not listening when several of the people on this forum cautioned you from using json.

I also suggest the you read the best answer on this stackoverflow thread

https://stackoverflow.com/questions/33437940/json-column-or-traditional-columns

1 like
martinbean's avatar

so how do i know uk is country, Newcastle is city and 3030 is postcode

@david001 As someone who lives in Newcastle, UK, I can tell you with confidence that “3033” is not a postcode. It’s not a postcode for anywhere in the UK 🙂

Please or to participate in this conversation.