Laravel路由语法错误排查:动态翻译路由名称生成链接问题
修复Laravel视图中的路由语法错误及相关问题
先来看你视图代码里引发语法错误的核心行:
<a class="btn btn-outline-light" href="<?php echo e(route('{{$flip->getTranslatedAttribute('opis')); ?>', app()->getLocale()) }}"><?php echo e(__('flipmenu.button')); ?></a> "><?php echo $flip->getTranslatedAttribute('name'); ?></a>
直接修复方案
把这段错误代码替换成:
<a class="btn btn-outline-light" href="{{ route($flip->getTranslatedAttribute('opis'), app()->getLocale()) }}">{{ __('flipmenu.button') }}</a>
错误原因解析
- 嵌套Blade语法错误:你在
route()函数里错误嵌套了{{ }}——Blade的{{ }}本身就是输出变量的语法,不需要在echo e()或者另一个Blade标签里再套一层。 - 符号与括号不匹配:原代码里的括号、单引号闭合混乱,还有多余的分号,导致PHP解析时抛出
syntax error, unexpected 'opis' (T_STRING), expecting ')'。 - 冗余HTML标签:原代码末尾多了一段
"><?php echo $flip->getTranslatedAttribute('name'); ?></a>,这会破坏HTML结构,必须删除。
额外需要注意的问题
1. 路由名称冲突
你的web.php里有三个路由指向同一个根路径/,还使用了不同的名称:
Route::get('/', 'FlipController@index')->name('menu'); Route::get('/', 'FooterController@index')->name('footer'); Route::get('/', 'MainController@index')->name('index');
Laravel只会识别最后一个定义的路由(name('index')),前两个menu和footer的路由名称会完全失效。建议调整路径:
Route::get('/menu', 'FlipController@index')->name('menu'); Route::get('/footer', 'FooterController@index')->name('footer'); Route::get('/', 'MainController@index')->name('index');
2. 确认opis字段的正确性
要确保flip模型的opis翻译字段里存储的是路由文件中定义的正确名称(比如farmyw、kariera这类),如果字段值不对,即使语法修复了,route()函数也会抛出路由未找到的异常。
3. 简化Blade循环代码
你可以把原生PHP风格的循环改成更简洁的Blade语法,提升可读性:
@foreach($flips as $flip) <div class="flip" farmy pv> <div class="front" style="background-image: url({{ Voyager::image($flip->image) }})"> <h1 class="text-shadow front-shadow">{{ $flip->getTranslatedAttribute('name') }}</h1> </div> <div class="back" style="background-color:#304c84;"> <h2>{{ $flip->getTranslatedAttribute('nameback') }}</h2> <p style="text-align: justify; color: white;">{{ $flip->getTranslatedAttribute('opis') }}</p> <a class="btn btn-outline-light" href="{{ route($flip->getTranslatedAttribute('opis'), app()->getLocale()) }}">{{ __('flipmenu.button') }}</a> </div> </div> @endforeach {{ $flip->button }}
内容的提问来源于stack exchange,提问作者Sebastian Kazanowski
相关产品推荐
相关产品推荐

