Laravel blade "undefined variable" 使用 route() 时出错
Laravel blade "undefined variable" error when using route()
作为一个项目,我正在构建一个类似 Whosebug 的论坛。在显示单个问题的页面上,我希望用户能够单击提问者的姓名并将其转发到相应的用户个人资料页面。我可以使用 {{ $question->user->name }}
从数据库中获取名称。添加 <a href=""></a>
部分时出现问题!
此外,个人资料页面有效。我可以访问它们,然后 url 例如说:../profile/1
.
这是 web.php 文件中的路由:
Route::get('/profile/{user}', 'PageController@profile')->name('profile');
这是 PageController 部分:
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile')->with('user', $user);
}
这是来自 show.blade 查看问题页面的代码,它不起作用:
<p>
Submitted by <a href="{{ route('profile', $user->id) }}">{{ $question->user->name }}</a>
</p>
我收到的错误消息是 Undefined variable: user
。
这让我感到惊讶,因为在个人资料页面上转发到特定问题适用于此 blade 代码:
<a href="{{ route('questions.show', $question->id) }}">View Question</a>
web.php 文件中的相应路径:
Route::resource('questions', 'QuestionController');
和问题控制器:
public function show($id)
{
$question = Question::findOrFail($id);
return view('questions.show')->with('question', $question);
}
我以为我在 PageController 中定义了变量 $user
,就像我在 QuestionController 中定义了 $question
一样?
//just change your like this way
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile',compact('user));
}
我可以看到您正在使用 Eloquent 关系模型。如果你想在问题上显示用户id,你可以使用Question
和User
之间的关系来找到发帖用户的id。
Submitted by <a href="{{ route('profile', $question->user->id) }}">{{ $question->user->name }}</a>
^^^^^^^^^
作为一个项目,我正在构建一个类似 Whosebug 的论坛。在显示单个问题的页面上,我希望用户能够单击提问者的姓名并将其转发到相应的用户个人资料页面。我可以使用 {{ $question->user->name }}
从数据库中获取名称。添加 <a href=""></a>
部分时出现问题!
此外,个人资料页面有效。我可以访问它们,然后 url 例如说:../profile/1
.
这是 web.php 文件中的路由:
Route::get('/profile/{user}', 'PageController@profile')->name('profile');
这是 PageController 部分:
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile')->with('user', $user);
}
这是来自 show.blade 查看问题页面的代码,它不起作用:
<p>
Submitted by <a href="{{ route('profile', $user->id) }}">{{ $question->user->name }}</a>
</p>
我收到的错误消息是 Undefined variable: user
。
这让我感到惊讶,因为在个人资料页面上转发到特定问题适用于此 blade 代码:
<a href="{{ route('questions.show', $question->id) }}">View Question</a>
web.php 文件中的相应路径:
Route::resource('questions', 'QuestionController');
和问题控制器:
public function show($id)
{
$question = Question::findOrFail($id);
return view('questions.show')->with('question', $question);
}
我以为我在 PageController 中定义了变量 $user
,就像我在 QuestionController 中定义了 $question
一样?
//just change your like this way
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile',compact('user));
}
我可以看到您正在使用 Eloquent 关系模型。如果你想在问题上显示用户id,你可以使用Question
和User
之间的关系来找到发帖用户的id。
Submitted by <a href="{{ route('profile', $question->user->id) }}">{{ $question->user->name }}</a>
^^^^^^^^^