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



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

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

结果是:

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

然而,我希望有更多的查询参数自动添加到url:

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

理想情况下,我想用刀片指令激活此功能

<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', ['bar'=>'baz']) }}">Hello world</a>
<a href="{{ route('cool') }}">Cool!</a>
<a href="{{ route('icecream', ['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>

我知道如何手动将查询参数添加到路线中。我知道如何定义刀片指令。

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

一种方法是声明全局函数。创建一个php文件。我将在app/Helpers/GlobalFunction.php的路径中将其命名为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>

最新更新