Home > other >  Access json data with Laravel and Inertia
Access json data with Laravel and Inertia

Time:06-20

I have a simple form with 1 input field and a submit button.

All that does is get the user input, match it with an external API, and submit both records to the database.

The response from the external API is JSON format, like this but I only want to retrieve the text field under choices

{
  "id": "123",
  "object": "tc",
  "created": 1655642237,
  "model": "text-code",
  "choices": [
    {
      "text": "paragraph text here",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ]
}

This is stored in a variable $complete so when I access it in the view, I get all of this with no way to target specific elements only.

This is my controller

public function index()
    {
        $prompts = Writer::all();

        return Inertia::render('Writer', [
            'prompts' => $prompts
        ]);
}

public function store(Request $request)
    {
        $complete = $start->complete([
             'engine' => '002',
             'prompt' => $request->input('inputText')
        ]);

        $data = json_decode($complete, true);

        Validator::make($request->all(), [
            'inputText' => 'required|min:5|max:255|string',
        ])->validate();

        Writer::create([
            'request' => $request->input('inputText'),
            'response' => $data['choices']
        ]);

        return redirect()->back()->with('message', 'success.');

}

I have to pass $complete to the create() method because passing $data gives an error

Array to string conversion

and

Object of class stdClass could not be converted to string

However if I return $data['choices'] right after the variable, I get the fields that are only under choices

The view is pretty simple

<div  v-for="prompt in $page.props.prompts">
    <div >
        <h5 >{{ prompt.request }}</h5>
        <p >{{ prompt.response }}</p>
    </div>
</div>

CodePudding user response:

In order to acces the data in the $choices-array (it's an array, not a string, and that's why you got an error accordingly), change the corresponding lines in your store-method to

Writer::create([
    'request' => $request->input('inputText'),
    'response' => $data['choices'][0]['text']
]);

But be aware that $data[ 'choices' ] could be empty, so before storing any value, make sure to check for existence and provide a default value, e.g.

$text = $data['choices'][0]['text'] ?? 'my-default-value';
  • Related