首页 > 解决方案 > 你知道为什么会出现这个错误吗?(在 null 上调用成员函数 formatLocalized())

问题描述

我有一个具有 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

解决方案


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

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

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

您可以使用 PHP 方法作为is_nullempty

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

推荐阅读