【问题标题】:Laravel Call to a member function getName() on null ErrorLaravel 在 null 错误上调用成员函数 getName()
【发布时间】:2021-03-13 01:15:53
【问题描述】:

我在 Laravel 帮助类中使用了一个自定义方法:

public static function get_lang()
{
    $title_tag = __( request()->path() . '.title_tag' );
    if( ( request()->route()->getName() !== 'index' ) ) {
        abort( 404 );
    }
}

当从 Web 上的浏览​​器访问时,它运行良好,没问题。

但是,当使用此 Artisan 命令在 CLI 上运行时,出现错误:

php artisan route:list

这是我得到的错误:

Error

Call to a member function getName() on null

at app/Helpers/Helper.php:11
public static function get_lang()
{
    $title_tag = __( request()->path() . '.title_tag' );
    if( ( request()->route()->getName() !== 'index' ) ) {
        abort( 404 );
    }
}

如何添加检查以验证 getName() 不为 null 以防止出现此错误?

【问题讨论】:

  • "[...] 检查以验证 getName() 不是 null [...]" - 你错过了你的错误所说的内容; request()->route()null,而不是 getName()null->getName() 无效。永远不要假设一个方法的结果,总是通过下面的答案来检查,或者如果在 PHP8 上,request()?->route()?->getName()(`null-safe 运算符)。

标签: php laravel


【解决方案1】:

在 CLI/控制台中,没有 request(),也没有 request()->route() 可以为其命名。

您可以考虑让您的助手检查 app()->runningInConsole() 并在那里返回默认值。

【讨论】:

  • 我喜欢这种方法,因为我可以在所有要在 Web 而不是控制台上运行的代码上使用它。谢谢。
【解决方案2】:

我相信当你运行命令时没有请求路由。这样的事情可以解决 getName() 无法在非对象上返回的问题。

public static function get_lang()
{
    $title_tag = __( request()->path() . '.title_tag' );

    // Validate that request()->route() is not null
    if(request()->route()) {
       if( ( request()->route()->getName() !== 'index' ) ) {
          abort( 404 );
       }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-06
    • 2020-07-16
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多