【问题标题】:How to return view with dynamic field in Laravel 6如何在 Laravel 6 中使用动态字段返回视图
【发布时间】:2020-01-22 22:36:36
【问题描述】:

我有一个名为profile.blade.php 的html 页面,其中包含一个锚标记:

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

我有这样的路线:

Route::get('/profile/{id}', 'ProfilesController@index')->name('profile');

我有一个ProfilesController,其中 index 方法返回一个拥有该配置文件的用户:

public function index()
{
   $userId = //somehow get the data sent from the anchor tag

   $user = $this->usersService->getProfileOwner($userId);

   return view("profile", [
      'user' => $user ?? []
   ]);
}

如何更改此代码,例如当 id 为 1 的用户访问 id 为 2 的用户的个人资料时,索引函数会将用户 2 的详细信息返回到blade 模板?

【问题讨论】:

  • 你试过request()-&gt;id吗?

标签: php laravel view routes


【解决方案1】:

Laravel 自带了一个方便的Route Model Binding,所以你可以使用依赖注入直接从路由 URL 中获取模型

public function index(User $user)
{
   return view("profile", [
      'user' => $user ?? []
   ]);
}
<a href="{{ route('profile', ['user' => $user]) }}">{{$user->name}}</a>
Route::get('/profile/{user}', 'ProfilesController@index')->name('profile');

【讨论】:

    【解决方案2】:

    Laravel 自动绑定类到方法

    use App\User;
    
    public function index(User $user)
    {
       return view("profile",compact('user'));
    }
    
    

    【讨论】:

      【解决方案3】:

      正如上面的答案,我建议你使用模型绑定。

      但是在你的代码中,你可以这样做:

      public function index($id)
      {
          $user = $this->usersService->getProfileOwner($id);
      
          return view("profile", [
             'user' => $user ?? []
          ]);
      }
      

      如果 $id 总是 int,你也可以 type-hint 它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-21
        • 1970-01-01
        • 2020-01-06
        • 2020-10-11
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多