【问题标题】:Error Call to a member function roles() on null (View: C:在 null 上调用成员函数角色()时出错(视图:C:
【发布时间】:2022-07-26 21:53:50
【问题描述】:

我现在正在经历这个错误,以前没有发生过,我一直在尝试排除故障,但没有解决。 以下是错误行代码。

                     Actions</th>

                                </tr>

                            </thead>

                            <tbody>

                                @php

                                    $count = 1;

                                @endphp

                                @foreach ($accounts as $account)

                                    <tr role="row" class="odd">

                                        <td class="sorting_1">{{ $count++ }}</td>

                                        <td>{{ date('F d, Y', strtotime($account->created_at)) 
                         }}</td>

                                        <td><label data-toggle="tooltip" title="{{ $account- 
               >status == 'completed' ? 'Confirmed on ' . date('F d, Y', strtotime($account- 
               >confirmed_at)) : 'pending confirmation' }}" style="border: none; background:

                                        @role('admin')

                                            <td><a href="{{ route('staff.edit', $account- 
              >createdBy) }}" target="_blank">{{ $account->createdBy->name }}</a></td>

                                            <td>

//错误指向

我已尽我所能,但没有解决办法。 请帮帮我

【问题讨论】:

  • $account-&gt;user-&gt;roles()-&gt;first()-&gt;name;如果任何-&gt; 调用返回null,则该代码将中断。在您的情况下,$account-&gt;usernull,而null-&gt;roles() 不起作用。您需要添加一些代码来处理它,例如 if ($account-&gt;user) { // Do something with $account-&gt;user-&gt;roles()-&gt;first() }

标签: laravel


【解决方案1】:
($account->user->roles()- >first()->name == 'agent')

该错误意味着 $account 没有用户,这意味着它为空,并且您正在尝试获取引发错误的空值的角色()。

在这种情况下,您会检查 $account 是否有用户。 一些快速的例子:

$account->user ? $account->user->roles()- >first()->name == 'agent' : // your else logic 

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 2018-01-14
    • 2017-08-09
    • 2020-01-19
    • 2017-09-14
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多