【问题标题】:Laravel blade "undefined variable" error when using route()使用 route() 时 Laravel 刀片“未定义变量”错误
【发布时间】: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


【解决方案1】:

我可以看到您正在使用具有关系的 Eloquent 模型。如果要在问题上显示用户id,可以使用QuestionUser之间的关系来查找发帖用户的id。

Submitted by <a href="{{ route('profile', $question->user->id) }}">{{ $question->user->name }}</a>
                                          ^^^^^^^^^

【讨论】:

    【解决方案2】:
    //just change  your  like this way
    
     public function profile($id)
    {
      $user = User::with(['questions', 'answers', 'answers.question'])->find($id);
      return view('profile',compact('user));
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-17
      • 2017-02-08
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 2014-03-15
      相关资源
      最近更新 更多