2

My db table structure

I'm using a view composer to get data from this table and send it back to my view

class NavComposer
{

 public function compose(View $view)
    {
        if (Auth::check()) {
            $view->with('unread_notifications', DB::table('notifications')->where([
                                            ['read_at', '=', NULL],
                                            ['notifiable_id', '=', Auth::user()->id],
                                            ])->get());
        }
    }
}

My view:

@foreach($unread_notifications as $notification)
{{ $notification->data }}
@endforeach

What I am getting:

{"id":79,"sender":"Diana","receiver":"Alex","subject":"Subject","body":"Lorem ipsum"}

What I want to display:

ID: 79
Subject: Subject
Body: Lorem Ipsum

I apologize in advance if this is very simple stuff I dont know much about JSON

2 Answers 2

3

You need to decode JSON. You can do this manually:

@foreach($unread_notifications as $notification)
    <?php $notificationData = json_decode($notification->data, true); ?>
    {{ $notificationData['sender'] }}
@endforeach

Or you can create accessor so Laravel could automatically convert JSON to an array:

public function getDataAttribute($value)
{
    return json_decode($value, true);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This did it!! Thank you very much ^_^
0
@foreach($unread_notifications as $notification)
   @foreach(json_decode($notification->data, true) as $d)
      <div>ID: {{ $d['id'] }}</div>
      <div>Subject: {{ $d['subject'] }}</div>
      <div>Body: {{ $d['body'] }}</div>
   @endforeach
@endforeach

2 Comments

Doesn't work, I get error: Trying to get property of non-object
@rmdy, Answer modified.

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.