【发布时间】:2019-12-31 18:47:11
【问题描述】:
作为一个项目,我正在构建一个类似论坛的 stackoverflow。在显示单个问题的页面上,我希望用户能够单击提问者的姓名并被转发到相应的用户个人资料页面。我可以使用{{ $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。
这让我感到惊讶,因为在个人资料页面上转发特定问题可以使用此刀片代码:
<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 一样?
【问题讨论】:
-
我在您的
QuestionController@show中没有看到任何$user。用户仅在PageController@profile -
有时使用类似 {{route('questions.show', ['id'=>$question->id]) }}
标签: php laravel routes laravel-blade laravel-routing