简体   繁体   中英

Tryind to display json object into blade php laravel

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>```

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.

看起来您的 title 属性不是对象,您应该先调试以检查它,使用dd()函数查看该属性的内部

看来我的专栏在可翻译的数组中,我只需要调用 getTranslation mehtod 和它的路径 col 和应用程序本地 jsu 就像{{getTranslation('title', 'en')}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM