1

my problem here in my code is I cannot store or insert array values in Database MySQL, here is my controller code please help me. thank you. My Code in Controller has no array or any so.. I dont have any clue how to turn it into array.

Controller

    public function store(Request $request)
{
    $this->validate($request,[
        'city' => 'required'

    ]); 


   $citi = new City;
   $citi->city = $request->input('city');
   $citi->save();

   return redirect('/lugar')->with('success', 'Data Inserted');
}

View

<td> {{Form::text('city[]', '', ['class' => 'form-control name_list', 'placeholder' => 'Add Country'])}} </td>
  • 1
    What errors are you getting? – petersowah Nov 24 '18 at 22:52
  • here, see _Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given _ –  Nov 24 '18 at 22:54
  • Possible duplicate of [Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given](https://stackoverflow.com/questions/46674623/argument-1-passed-to-illuminate-database-grammarparameterize-must-be-of-the) – George Udosen Nov 24 '18 at 23:01
  • it is not laravel it is pure php. i dont understand :( –  Nov 24 '18 at 23:17

2 Answers2

0

You can't store arrays in MySQL, its different if you compared it with Mongo (NoSQL).

What you can do is, turn that array into a json string. So json_encode($request->city) and save it.

Then if you want to modify it's values once retrieved from DB, you can use json_decode($data->city) which turns it back to an array.

Adis Azhar
  • 1,022
  • 1
  • 18
  • 37
0

you can actually save this using serialize or json_encode.

Using serialize:

$citi->city = serialize($request->input('city'));

Using json_encode:

$citi->city = json_encode($request->input('city'));

then just use unserialize and json_decode on your blade file.

kapitan
  • 2,008
  • 3
  • 20
  • 26
  • how can I unserialized it?? –  Nov 25 '18 at 01:23
  • Arrays are now in my database but they are serialized.. how can I unserialized them? they have the value of this **a:2:{i:0;s:7:"New York";i:1;s:8:"Chicago";}** –  Nov 25 '18 at 01:25
  • hey @kapitan, all works fine except for the **a:2:{i:0;s:7:** for this serial code.. can i remove that and change it to normal? help me so i can upvote your answer and marked it as an asnwer ty –  Nov 25 '18 at 01:34
  • unserialize($myvariable) or json_decode($myvariable) – kapitan Nov 26 '18 at 01:55