为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 语言切换器,将附加参数传递给路由

Laravel 语言切换器,将附加参数传递给路由

PHP
有只小跳蛙 2023-07-01 17:11:17
我真的想不出一个优雅的解决方案来解决这个问题,所以这里是:这是 app.blade.php 中用于语言切换器的刀片代码:  <language-switcher                                locale="{{ app()->getLocale() }}"                                link-en="{{ route(Route::currentRouteName(), 'en') }}"                                link-bg="{{ route(Route::currentRouteName(), 'bg') }}"                            ></language-switcher>这是我的一些路线Route::redirect('/', '/en');Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify');Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');Route::group([    "prefix" => '{language}',    'where' => ['language' => '(en||bg)'],], function () {    //Auth routes    Auth::routes();    //Returns to home    Route::get('/', 'HomeController@index')->name('home');    //Handles the faq routes    Route::resource('faq', 'FaqController');});Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');});它适用于不需要任何获取参数的页面,例如:登录/注册/主页,但是如果我使用需要像 faq.edit 这样需要 {id} 参数的页面 - 语言切换器将抛出错误,因为我没有向它传递 {id} 参数。我能想到的唯一解决方案是在子刀片视图中添加语言切换器,然后从那里传递所需的参数,但这意味着我必须将语言切换器添加到每个子视图,而不是只在父视图中添加一次。
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

您可以通过以下步骤来实现:

  • 实现一个 URL 生成器宏,这将更容易生成 URL,除了语言之外,这些 URL 必须相同

  • 获取当前路由的参数

  • 将所选语言合并到其中

<?php


namespace App\Providers;


use Illuminate\Routing\UrlGenerator;

use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider

{

    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }


    /**

     * Bootstrap any application services.

     *

     * @return void

     */

    public function boot()

    {

        UrlGenerator::macro('toLanguage', function (string $language) {

            $currentRoute = app('router')->current();

            $newRouteParameters = array_merge(

                $currentRoute->parameters(), compact('language')

            );

            return $this->route($currentRoute->getName(), $newRouteParameters);

        });

    }

}

在你的 Blade 文件中


@inject('app', 'Illuminate\Contracts\Foundation\Application')

@inject('urlGenerator', 'Illuminate\Routing\UrlGenerator')


<language-switcher

    locale="{{ $app->getLocale() }}"

    link-en="{{ $urlGenerator->toLanguage('en') }}"

    link-bg="{{ $urlGenerator->toLanguage('bg') }}"

></language-switcher>

您会注意到我使用契约注入而不是使用外观。


查看完整回答
反对 回复 2023-07-01
  • 1 回答
  • 0 关注
  • 103 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信