Laravel Blade中如何用{{ }}生成@+变量形式的路由链接?
example.com/@username using Laravel Blade's {{ }} syntax? 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.
2. Named Routes + Route Parameters (Recommended)
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

