1

I have a single column in db named session and I want to insert all below data in single column in a form of array.

data available in array

 array:1 [▼
0 => array:3 [▼
"_token" => "ENzbpMgvlOhMkwE1Fv13hjn9NlCOUolIFBDZ4wJd"
"session_start" => "2000-01-01"
"session_end" => "2002-01-01"
]
]

I tried below

public function store(Request $request)
{
  $arr = (array($request->all()));

  $create = SchoolSession::create($arr));
}

getting an error: Array to string conversion

Please advise the solution and also advise how to fetch the same from db and show seperately.

1
  • please have a look at this Commented Mar 18, 2020 at 11:18

2 Answers 2

2

You can't insert an array into a database field without some kind of serialization, so you may try something like this (but there's a better way, continue reading):

public function store(Request $request)
{
    $json = json_encode($request->all());

    $create = SchoolSession::create(['session' => $json]);
}

Make sure your database field type is JSON/TEXT depending on your mysql version. When retrieving the data you also need to decode it.

Out of the box, Laravel provides an easy mechanism to handle this. So, you don't need to manually encode/decode your data. Eloquent will take care of encoding brfore saving it to database and also the decoding will be handled automatically. Read the doc (link given above).

Sign up to request clarification or add additional context in comments.

3 Comments

I used json_encode to insert it works but when i use decode its showing me data ins this form {"_token":"ENzbpMgvlOhMkwE1Fv13hjn9NlCOUolIFBDZ4wJd","session_start":"2000-01-01","session_end":"2002-01-01"}
To decode a json string to an array, you should use json_decode($data, true). This will return an array instead of an object (stdClass).
0

You can not directly add array in the column:

public function store(Request $request)
{
    $arr = $request->all();
    $arr = serialize($arr);
    $create = SchoolSession::create(['session'=>$arr]);
}

And to fetch the same from DB:

public function view(Request $request)
{

    $SchoolSession = SchoolSession::where('id','Specific ID ADD')->get();
    $SchoolSession = unserialize($SchoolSession[0]->session);
}

2 Comments

getting error Call to undefined function Symfony\Component\Routing\serialize()
@MuhammadKazim Which laravel version have you used?

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.