Jeremy
Jeremy

Reputation: 206

How to store several data in this case with Laravel?

I'm sending an array of data with axios that looks like this :

originalData:Object
  19:"ae"
  20:"aze"
  21:"aze"
  22:"aze"
  23:"aze"
  24:"aez"
  79:"az"
  80:"aza"
  81:"az"
  83:"az"

Each id corresponds to the id of a question. And each text of the id corresponds to his answer.

My table answers contains this structure :

id, answer, user_id, question_id

I would like to create new lines in the database for each answer. The id must be stored in the column question_id and the text in the columnanswer

I tried something like this:

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

        $finalArray = [];

        foreach ($data as $key => $value) {
            array_push($finalArray, [
               'user_id' => auth()->user()->id,
               'question_id' => ??,
               'answer' => ??
            ]);
        }

        Answer::insert($finalArray);
    }

I don't know if it's the right method. In any case, I don't know how to get the id and the text of the question in this case.

Can you help me ?

Thank you

Upvotes: 2

Views: 35

Answers (1)

mare96
mare96

Reputation: 3869

I think you can do like this:

public function store(Request $request)
    {
        $data = $request->all();
        foreach ($data as $key => $value) {
            Answer::create([
                 'user_id' => auth()->user()->id,
                 'question_id' => $key, // $key will be 19, 20...
                 'answer' => $value // $value 'ae', 'aze' ...
            ]);
        }
    }

This should work fine. If you have any error provide it here.

Good luck!

Upvotes: 1

Related Questions