【问题标题】:Laravel route Call to a member function getName() on nullLaravel 路由在 null 上调用成员函数 getName()
【发布时间】:2021-02-14 11:32:39
【问题描述】:

对于包含导航项数组的管理站点导航,我有一个非常简单的特征。我有另一种方法来检查路线并为项目设置活动类。它在浏览器中运行良好,但在终端中使用 artisan 给我以下错误。

特征方法

protected function getActiveClass($routeName)
{
    return (Route::current()->getName() == $routeName) ? 'active' : NULL;
}

Symfony\Component\Debug\Exception\FatalThrowableError : 调用 成员函数 getName() on null

特征完整代码

namespace App\Traits;


use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;

trait AdminMenu
{

    /**
     * @return array
     */
    public function navItems()
    {
        $sideNavItems = [
            [
                'nav'    => 'dashboard',
                'label'  => __('admin.menu.dashboard'),
                'icon'   => 'tachometer-alt',
                'route'  => route('admin.dashboard'),
                'active' => $this->getActiveClass('admin.dashboard'),
            ],

            ...

        ];

        View::share('navItems', $sideNavItems);
    }

    /**
     * @param $routeName
     *
     * @return string|null
     */
    protected function getActiveClass($routeName)
    {
        return (Route::current()->getName() == $routeName) ? 'active' : NULL;
    }
}

【问题讨论】:

    标签: laravel routes


    【解决方案1】:

    好的,解决了。通过检查当前路由来包裹条件。

    protected function getActiveClass($routeName)
    {
        if (Route::is($routeName)) {
            return (Route::current()->getName() == $routeName) ? 'active' : NULL;
        }
    
        return NULL;
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用

      if ($request->route()->named($routeName)) {
           return 'active';
      }
      
      return NULL;
      

      Laravel Inspecting The Current Route

      【讨论】:

        【解决方案3】:

        我正在使用它来获取当前路线名称

        @if (request()->route())
        @if (in_array(request()->route()->getName(), @$settings->getArray()))
        
        @endif
        @endif
        

        通过检查顶部request()->route(),我们可以避免null 错误。 request()->route()->getName() 将给出路线名称。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-04
          • 2016-06-29
          • 2018-04-03
          • 2021-10-06
          • 2019-06-17
          • 2020-10-22
          • 2018-02-11
          相关资源
          最近更新 更多