Home > other >  Tryind to display json object into blade php laravel
Tryind to display json object into blade php laravel

Time:06-20

i'm trying to display this json column into blade file

But i get Trying to get proprty 'en' of non object

    <tr>
        <th>Title en</th>
        <th>Title ar</th>
        <th>Description</th>
        <th>Session Number</th>
        <th>Session Per Week</th>
        <th>Session Duration</th>
        <th>Show</th>
    </tr>
    @foreach($model as $program)

        <tr>
            <th>{{json_decode($program->title)->en}}</th>
            <th>{{json_decode($program->title)->ar}}</th>
            <th>{{$program->description}}</th>
            <th>{{$program->sessions_number}}</th>
            <th>{{$program->sessions_per_week}}</th>
            <th>{{$program->session_duration}}</th>
            <th>{{$program->is_shown ? 'Yes' : 'No'}}</th>

        </tr>
    @endforeach
    </thead>```

CodePudding user response:

if your JSON format is something like

{"en":"title", "ar":"other-title"}

Then it should work.

My best guess is the en key doesn't exist on that title property.

If you are using the latest PHP then you can use the Nullsafe operator (?->) if not then use the isset check or use the null coalescing operator ??

 <th>{{json_decode($program->title)->en ?? '' }}</th>

Also, be sure that $program->title itself is not null doing something like:

@php $title = isset($program->title) ? json_decode($program->title): null @endphp 
   <th>{{$title->en ?? '' }}</th>

But it is better to create a Accessor for this type of thing in the eloquent model. So you can directly do something like

$program->en_title;

So the blade file is clean and easy to understand but I don't suggest to go Accessor path if you are not reusing the code even if it makes the code cleaner. It is just my preference.

CodePudding user response:

It looks like your title property is not an object, you should debug first to check it out, use dd() function to see inside this property

  • Related