如何自动向 Laravel Blade 模板中的所有链接添加一些查询参数?

问题描述

我使用的是 Laravel 8。 我使用 route() 助手在 Blade 模板中显示一些链接

    <a href="{{ route('foo',['bar'=>'baz']) }}">Hello world</a>

结果如下:

    <a href="https://example.com/foo?bar=baz">Hello world</a>

但是,我希望有更多的查询参数自动添加到网址:

    <a href="https://example.com/foo?bar=baz&src=mailing">Hello world</a>

理想情况下,我想使用 Blade 指令激活此功能

<a href="{{ route('foo',['bar'=>'baz']) }}">Hello world</a>
<a href="{{ route('cool') }}">Cool!</a>
<a href="{{ route('icecream',['flavour'=>'strawBerry']) }}">StrawBerry icecream</a>

<hr>

@withqueryparams(['src'=>'mailing'])
{{-- same code here,but the result will differ --}}
<a href="{{ route('foo',['flavour'=>'strawBerry']) }}">StrawBerry icecream</a>
@withendqueryparams
<a href="https://example.com/foo?bar=baz">Hello world</a>
<a href="https://example.com/cool">Cool!</a>
<a href="https://example.com/icecream/strawBerry">StrawBerry icecream</a>

<hr>
    
<a href="https://example.com/foo?bar=baz&src=mailing">Hello world</a>
<a href="https://example.com/cool?src=mailing">Cool!</a>
<a href="https://example.com/icecream/strawBerry?src=mailing">StrawBerry icecream</a>

我知道如何手动向路由添加查询参数。 我知道如何定义 Blade 指令。

但是,我不知道如何自动查询参数添加到解析的路由中。

解决方法

一种方法是声明全局函数。创建一个php文件。我将在 GlobalFunction.php

的路径中将其命名为 app/Helpers/GlobalFunction.php
<?php

if(!function_exists('queryParam')) {

    function queryParam($routeName,$params=[]){

        $params['src']="mailing";

        return route($routeName,$params);
    }
}

甚至改进如下所示的 queryParam 方法

    function queryParam($routeName,$params=[],$default=['src'=>'mailing']){
            
            return route($routeName,array_merge($params,$default));
   }

并在 composer.json 自动加载文件中

"autoload": {
        "psr-4": {
            "App\\": "app/","Database\\Factories\\": "database/factories/","Database\\Seeders\\": "database/seeders/"
        },"files": ["app/Helpers/GlobalFunction.php"]
    },

然后运行composer dump-autoload

在你看来

 <a href="{{ queryParam('foo',['bar'=>'baz','name'=>'john']) }}">Hello world</a>
,

你可以使用这样的代码

@php
    $params = ['bar'=>'baz'];
    if (conditions) {
        $params['src'] = 'mailing';
    }
@endphp

<a href="{{ route('foo',$params) }}">Hello world</a>