How to insert a serialize into the database in a string field

Asked

Viewed 109 times

-2

Guys, I have an app Laravel and I am needing to insert a value that is going through a first serealize() in PHP in my database in a field string.

This is the array

$dia_semana = array(serialize($request->dia_semana));

dd($dia_semana);

This is the result:

array:1 [▼
  0 => "a:3:{i:0;s:1:"0";i:1;s:1:"1";i:2;s:1:"2";}"
]

I need it inserted into the field "weekday (string/varchar)" in the bank as follows 0, 1, 2, 3 being 0-second, 1-third, 2-fourth and so on. This field is a checkbox in my application it can mark 1 or several days.

First of all, I’m not sure I needed the array() before serialize.

If I remove mine dd() the code falls on my catch() returning

Array to string Conversion

I believe that precisely because of the above problem array untreated.

  • 1

    Think to me, if you want to save a string, why create an array?

  • opa, good morning Andy, he already creates an array by serialize brother, let’s say, transform this serialize array into "0,1,2".

  • How do you create the array by serialize? It’s not by array() that you create the array?

  • what I meant was that with the array() or he no longer becomes one "array" by serealize

  • That doesn’t make sense. By itself documentation of the function itself serialize returns a string.

  • By the way, why are you Serializing your object? If $request->dia_semana is a array, then it wouldn’t be enough to do join(', ', $request->dia_semana)?

  • opa, already got here what I wanted, I did what the friend Orge below said using $casts and then used the implode $dia = implode(',', $request->dia_semana); the result was what I expected "1,2,3", thanks anyway.

Show 2 more comments

2 answers

2


  • thanks Thanks for the help, I used $Casts and then used the implode $dia = implode(',', $request->dia_week); the result was what I expected "1,2,3", thank you.

-2

I would use a column of type json, mysql and postgresql already allow for example, pass a json_encode with desired information to save in this column, and use $cast as the friend said.

The advantage of using the json type in the database is that you will be able to search inside a json object without problems =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.