【问题标题】:Do you know why this error is appearing? (Call to a member function formatLocalized() on null)你知道为什么会出现这个错误吗? (在 null 上调用成员函数 formatLocalized())
【发布时间】:2018-05-09 20:05:22
【问题描述】:

我有一个具有 index() 方法的 UserController,该方法应该获取用户过去在会议中的所有注册,并为每次注册获取会议详细信息:

我有以下代码来获取用户在会议中的过去和下一次注册:

 public function index(Request $request){

        $user = $request->user();

        $pastRegistrations = $user->registrations()->with(['conference' => function ($query) {
            $query->where('conf_end_date', '<', now());
        }])->get();

        $nextRegistrations = $user->registrations()->with(['conference' => function ($query) {
            $query->where('conf_end_date', '>', now());
        }])->get();

        return view('users.index',
            compact('user', 'pastRegistrations','nextRegistrations'));
    }

要在 index.blade.php 中显示,有这个 foreach:

 @foreach($nextRegistrations as $nextRegistration)
    <li class="list-group-item">
        <p  {{optional($nextRegistration->conf)->conf_start_date->formatLocalized('%a, %b %d, %Y - %H:%M')}}</p>
        <h5>{{optional($nextRegistration->conf)->title}}</h5>
        <p Registration in {{$nextRegistration->conf->created_at }}</p>
    </li>
@endforeach

但是显示结果时 $nextRegistrations 出现错误:

Call to a member function formatLocalized() on null

<?php echo e(optional($nextRegistration->conf)->conf_start_date->formatLocalized('%a, %b %d, %Y - %H:%M')); ?></p>

问题只是:

   <p  {{optional($nextRegistration->conf)->conf_start_date->formatLocalized('%a, %b %d, %Y - %H:%M')}}</p>

只有这个有效:

<h5>{{optional($nextRegistration->conf)->title}}</h5>
            <p Registration in {{$nextRegistration->conf->created_at }}</p>

【问题讨论】:

    标签: laravel


    【解决方案1】:

    当您尝试格式化不存在的内容时,PHP 错误并不奇怪。基本上你自己给了答案:

    但是当没有下次注册时,$nextRegistrations 中会出现错误

    在尝试对其调用方法之前,您必须检查$nextRegistrations 是否为空。

    您可以使用 is_nullempty 等 PHP 方法:

    @if(!empty($nextRegistration->conf || !empty($nextRegistration->conf->conf_start_date))
        {{ ... }}
    @endif
    

    【讨论】:

    • 谢谢,但是用 "{{!empty(($nextRegistration->conf)->conf_start_date->formatLocalized('%a, %b %d, %Y - %H:%M' ))}}” 出现“试图获取非对象的属性”。
    • 更新了我的答案
    • 谢谢,但仍然出现“尝试获取非对象的属性”。
    • 如果有下次注册还是会出现这个错误。
    • 那么错误在其他地方,因为它肯定不在我的答案中:p
    猜你喜欢
    • 1970-01-01
    • 2023-01-20
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2020-01-19
    • 2017-09-14
    • 2017-06-18
    相关资源
    最近更新 更多