0

I have a checkbox with multiple values to be selected. So far I got it working and the data is inserting into the database but it's in this format,

The image shows the values being 1,2,3

My issue is that I want the data to be in this format ["value1","value2","value3"]. I'm using Laravel and this is the code in my controller:

public function store(NewsRequest $request) //ive removed most of the unnecessary code like the image upload and all to make this clean.
{
    $news = new News($request->except('files', 'image'));
    $serialize = implode(",", $news->majors); //this is my focus to change the format to ["value1","value2","value3"]

    //ready data for insertion
    $data = array(
        "name" => $news->name,
        "article_type_id" => $request->category,
        "majors" => $serialize,
        "content" => $news->content
    );

    DB::table('articles')->insert($data); //insert into database
}

Currently I'm only able to insert the data with a comma separating them but I want the data to be inserted like the following:

enter image description here

I tried looking around the internet but I couldn't find anything that could help besides JSON.stringify. I'm hoping to get the format in my controller itself. I'm hoping to get some insight for this. Thank you in advance.

6
  • 2
    just add quotation marks as part of implode string - implode('","', $news->majors); and concatenate same quotation marks at beginning and end of the produced string. Commented Jan 14, 2020 at 9:50
  • 1
    try this: '['.implode('","', $news->majors).']' Commented Jan 14, 2020 at 9:53
  • Have you tried json_encode($news->majors)? Commented Jan 14, 2020 at 9:56
  • Thank you both! '['.implode('","', $news->majors).']' did the trick! :) Commented Jan 14, 2020 at 9:56
  • Do not do this. Data in a database needs to be normalised otherwise you will have problems further down the road. Use relationships Commented Jan 14, 2020 at 9:57

2 Answers 2

2

adding quotation marks at the beginning , within implode() and at the end will do the magic.

$serialize = '["'.implode('","', $news->majors).'"]';
Sign up to request clarification or add additional context in comments.

Comments

0

You can consider using json attribute for column in migration file and then in related model you can cast that column as array

Comments

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.