首页 > 后端开发 > php教程 > 使用URL默认来简化Laravel中的路由参数

使用URL默认来简化Laravel中的路由参数

James Robert Taylor
发布: 2025-03-06 01:41:09
原创
365 人浏览过

在Laravel应用程序中管理URL参数,尤其是那些具有多种语言或复杂路由模式的那些

Streamlining Route Parameters in Laravel Using URL Defaults

可以重复。 Laravel通过URL默认提供了优雅的解决方案,使您可以为URL参数设置范围范围的默认值。让我们探索这个功能强大的功能的实现。

>

#Underding URL默认值

URL默认值使您可以在应用程序上定义URL参数的全局默认值。事实证明,对于处理语言偏好或区域设置等通用参数尤其有价值。

>

>让我们在具有货币支持的多语言应用程序中实现URL默认值
<!-- Syntax highlighted by torchlight.dev --><?php

namespace App\Http\Middleware;

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

class SetUrlDefaults
{
    public function handle(Request $request, Closure $next)
    {
        URL::defaults([
            &#39;locale&#39; => $request->user()?->preferred_language ?? config('app.locale'),
            'currency' => $request->user()?->preferred_currency ?? 'USD'
        ]);
        return $next($request);
    }
}
登录后复制

在内核中注册中间件:

<!-- Syntax highlighted by torchlight.dev --><?php

namespace App\Http;

class Kernel extends HttpKernel
{
    protected $middleware = [
        // ... other middleware
        \App\Http\Middleware\SetUrlDefaults::class,
    ];
}
登录后复制

实现路由结构:

<!-- Syntax highlighted by torchlight.dev --><?php

use App\Http\Controllers\ProductController;

Route::prefix(&#39;{locale}/{currency}&#39;)->group(function () {
    Route::get('products', [ProductController::class, 'index'])
        ->name('products.index');

    Route::get('products/{product}', [ProductController::class, 'show'])
        ->name('products.show');
});

class ProductController extends Controller
{
    public function index()
    {
        // URLs will automatically use default locale and currency
        return view('products.index', [
            'products' => Product::paginate(20),
            'categoryUrl' => route('products.category', ['category' => 'electronics'])
        ]);
    }

    public function changePreferences(Request $request, $locale, $currency)
    {
        $request->user()->update([
            'preferred_language' => $locale,
            'preferred_currency' => $currency
        ]);

        return redirect()->back();
    }
}
登录后复制

在您的视图中,您可以在不明确指定默认值的情况下生成URL:

>
<!-- Syntax highlighted by torchlight.dev --><!-- Products listing view -->
<nav>
    <a href="{{ route(&#39;products.index&#39;) }}">{{ __('All Products') }}</a>
    <a href="{{ route(&#39;products.show&#39;, $product) }}">{{ $product->name }}</a>
</nav>

<!-- Only override when needed -->
<a href="{{ route(&#39;products.index&#39;, [&#39;currency&#39; => 'EUR']) }}">
    {{ __('View in Euros') }}
</a>
登录后复制

此实现提供干净,可维护的路由,同时自动处理您的应用程序的用户首选项。

以上是使用URL默认来简化Laravel中的路由参数的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板