【问题标题】:BadMethodCallException in Macroable.php line 81: Method defaults does not existMacroable.php 第 81 行中的 BadMethodCallException:方法默认值不存在
【发布时间】:2017-10-14 12:22:35
【问题描述】:

根据文档Setting Default Url Values,我收到了BadMethodCallException 从中间件设置 URL 的默认参数。

这是我的代码

类 SetDefaultLocaleForUrls

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        $locale = $request->route()->parameter('locale');
        $site_locales = ['en','es','fr','de','zh','tw','nl','pt'];

        if(!empty($locale) && !in_array($locale,$site_locales)){
            $locale = 'en';
        }

        if (empty($locale)) {
            $locale = 'en';  //default locale
        }

        if (empty($locale)) {
            $locale = 'en';  //default locale
        }

        URL::defaults(['locale' => $locale]);

        return $next($request);
    }
}

我的路线配置

Route::get('/{locale?}/about-us', ['as' => 'frontend.about-us.localized', 'uses' => 'Frontend\AboutUsController@index'])->middleware('locale');

我在受保护的 $routeMiddleware 中的中间件配置

'locale' => \App\Http\Middleware\SetDefaultLocaleForUrls::class,

我该如何解决?

【问题讨论】:

    标签: php laravel-5.5


    【解决方案1】:

    仔细检查路由中间件中的 namespaceuse 语句:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\URL;
    
    class SetDefaultLocaleForUrls
    {
        public function handle($request, Closure $next)
        {
            URL::defaults(['locale' => $request->user()->locale]);
    
            return $next($request);
        }
    }
    

    更新:

    我已将您的代码放入 Laravel 的实例中,但没有收到任何错误。 PHPStorm 报告Method 'defaults' not found in \Illuminate\Support\Facades\URL,但它不会导致 BadMethodCallException,所以我认为这仅与我的 PHPStorm 配置有关。

    SetDefaultLocaleForUrls 类中我添加了

    app()->setLocale($locale);
    

    这在根据我输入的 URL 在我的视图中显示数据方面工作正常。这是在我的视图中使用检查,例如:

    @if (App::isLocale('de'))
        <h1>Guten Morgen</h1>
    @else
        <h1>Good Morning</h1>
    @endif
    

    但是,如果我输入的 URL 不在您的 $site_locales 数组中,它不会像我预期的那样更新 URL。但是,它确实将语言环境设置为您的默认 en 并在视图中显示正确的数据。

    该方法是否打算重写 URL?

    您可以尝试与 BadMethodCallException 相关的一件事是清除您的路由缓存:

    php artisan route:clear
    

    【讨论】:

    • 能否请您在设置默认值的位置发布文件
    • 是的,我正在更新答案,请稍候
    • 删除 ?从路线。应该只是 {locale}
    • 不工作,我也试过了,但是它是一个可选参数,主要问题是 URL::defaults(['locale'=>$locale]);命令
    • 如何将变量$locale 更改为$set_locale(例如)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2017-03-28
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多