Bradley Kirkland
Bradley Kirkland

Reputation: 682

Laravel separate array into table fields

I have a table, data has been passed to it, and is being stored. I want to separate it into different columns of a table to make it easily readable.

When I use:

<td>{{$message->Content['text']}}</td>

I get the error: Trying to access array offset on value of type null (View: VIEWSDIRECTORY).

This is the dump of what seems to be pulling, I am trying to return the "text":"SPOCK" as I can then repeat the process for each one section i.e type:

 {
        #attributes: array:11 [
    "id" => "b5ef7556-c208-40b0-8bfa-1358bf482cd0"
    "method" => "sms"
    "msisdn" => 6422
    "direction" => "mo"
    "type" => "suggestion"
    "status" => "received"
    "content" => "{"senderPhoneNumber":"+6422","messageId":"Ms5ppMnxRHTw26gFSRwbsvAA","sendTime":"2020-06-05T03:20:58.506749Z","suggestionResponse":{"postbackData":"49da99a5-bc85-4efd-9587-54c335e7f329","text":"SPOCK","type":"REPLY"}}"
    "suggestion_id" => "49da99a5-bc85-4efd-9587-54c335e7f329"
    "created_at" => 1591327269
    "updated_at" => 1591327269
    "deleted_at" => null
  ]

My controller:

    {
        $message = Message::find($id);

        return view($message->direction . $message->type, compact('message'));
    }
}

Blade:

            <thead>
                <tr>
                    <th scope="col">MESSAGE ID</th>
                    <th scope="col">MESSAGE</th>
                </tr>
            </thead>

            <tbody>
            <tr>
                <td style='font-size:14px'>{{$message->id}}</td>    
            <td>{{$message->Content['text']}}</td>

My Message Model:

    /**
     * Get the suggestions for this message.
     */
    public function suggestions()
    {
        return $this->hasMany(Suggestion::class);
    }

    public function getContentAttribute($value)
    {
        return json_decode($value);
    }

Upvotes: 0

Views: 325

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

Looks like (not clear in the question) that the JSON you posted is the value of the content field of your Message model, right? If so, you are trying to access text directly while its inside the Response property.

So your view should be like:

<td>{{$message->content->Response->text}}</td>

Upvotes: 1

Related Questions