【问题标题】:Laravel routes returning incorrect model to viewLaravel 路由返回不正确的模型以查看
【发布时间】:2020-08-13 21:49:57
【问题描述】:

我的 Laravel 应用程序中的“显示”和“编辑”路由通过 eloquent 查询检索到正确的模型,但返回到视图的模型始终相同。我已经清除了我的路由缓存,但没有运气。

网络路由:

    Route::get('/teams/{id}/edit', function($id) {
        $team = \App\Team::find($id);
        return view('teams.edit', ['team', $team]);
    });

无论将哪个 id 传递给函数,视图始终显示 id 为 9 的团队

奇怪的是,如果我在路线封闭内返回团队,它会显示正确的团队。

dd($team)的结果

Team {#479 ▼
  -name: null
  -company_id: null
  #fillable: array:2 [▼
    0 => "name"
    1 => "company_id"
  ]
  #connection: "mysql"
  #table: "teams"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:6 [▼
    "id" => 31
    "company_id" => 14
    "name" => "Initial 3 5.0"
    "current_session_id" => 0
    "created_at" => "2019-12-30 16:17:40"
    "updated_at" => "2019-12-30 16:17:40"
  ]
  #original: array:6 [▼
    "id" => 31
    "company_id" => 14
    "name" => "Initial 3 5.0"
    "current_session_id" => 0
    "created_at" => "2019-12-30 16:17:40"
    "updated_at" => "2019-12-30 16:17:40"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

【问题讨论】:

  • 你的代码显然是对的,试试php artisan optimize
  • @JesusValera 从 Laravel 5.5 开始,不再需要 php artisan optimize。
  • 将数据传递给视图的正确语法是return view('teams.edit', ['team' => $team]);
  • @kerbholz 这会产生相同的结果。
  • "{{ dd($team) }} 在视图中不返回相同的团队" 应该,给定您的代码。您要么有一个 View Composer,要么在某处执行了篡改您的(视图)数据的其他东西。在您看来,您访问的是{{ $team->company_id}} 还是{{$theTeam->company_id}}?祝你好运

标签: php laravel eloquent routes


【解决方案1】:

试试我下面的例子

Route::get('/teams/{id}/edit', function($id) {
        $team = \App\Team::find($id);
        return view('teams.edit')->with('team', $team);
    });

通常,您有三个选项可以将数组传递给视图。

return view('teams.edit')->with('team', $team);

return view('teams.edit')->withTeam($team);

return view('teams.edit')->with(compact('team'));

在视图中访问它就像

{{$team->id}}

【讨论】:

  • 不幸的是,这些示例产生了相同的结果。
  • 不确定return view('teams.edit')->with(compact('team'));,不应该是return view('teams.edit', compact('team'));吗?
  • @kerbholz return view('teams.edit', compact('team')); 返回相同的结果。
【解决方案2】:

罪魁祸首是AppServiceProvider内部的视图作曲家...

        //compose all the views....
        view()->composer('*', function ($view) 
        {
            if (Auth::check()){

                $team = Team::find(Auth::user()->team_id);
                $view->with('team', $team );    
            }
        });  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2021-05-27
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多