You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Blade中如何用{{ }}生成@+变量形式的路由链接?

I want to format my user profile route as example.com/@username, and generate links to this route in Blade templates. I tried writing:

<a href="/@{{ $user->name }}">Go to {{ $user->name }} profile</a>

But the {{ $user->name }} inside the href attribute gets escaped as a literal, resulting in the actual jump address being example.com/{{ $user->name }}. I know I can use native PHP (like @<?= $user->name; ?>), but I want to use Laravel's {{ }} syntax. Is this possible?


Absolutely! You don't need to fall back to native PHP—there are several clean ways to do this using Blade's {{ }} syntax:

1. String Concatenation

Simply concatenate the @ symbol with your user name variable within the Blade echo:

<a href="/{{ '@' . $user->name }}">Go to {{ $user->name }} profile</a>

Blade will first resolve '@' . $user->name to produce @username, then insert it into the href attribute, giving you the correct /@username path.

For a more maintainable approach, define a named route in your routes/web.php:

Route::get('/@{username}', [UserProfileController::class, 'show'])->name('profile.show');

Then use Laravel's route() helper in your Blade template to generate the link:

<a href="{{ route('profile.show', ['username' => $user->name]) }}">Go to {{ $user->name }} profile</a>

This follows Laravel's best practices—if you ever need to change the route structure later, you only have to update the route definition instead of every instance of the link in your templates.

3. Variable Interpolation in Double Quotes

You can also leverage PHP's double-quoted string interpolation for a more concise write-up:

<a href="/{{ "@$user->name" }}">Go to {{ $user->name }} profile</a>

PHP will parse the variable inside the double quotes, turning @$user->name into @username before Blade renders it into the final HTML.


内容的提问来源于stack exchange,提问作者Abdullah Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:17:49