【问题标题】:Laravel5.8 Model Binding Route Arg 1 passed must be an instance of ModelLaravel5.8 Model Binding Route Arg 1 传递的必须是Model的实例
【发布时间】:2019-10-11 01:42:52
【问题描述】:

Laravel 项目通过本地化实现并且运行良好。进行自定义,因为用户可以将语言(区域设置)保存在 DB 中,问题就来了。

  1. 用户能够在数据库中保存语言。
  2. 当用户尝试编辑语言(区域设置)时,就会出现此问题。

传递给 App\Http\Controllers\CustomizeController::edit() 的参数 1 必须是 App\Model\Customize 的实例,给定字符串

在 CustomizeController.php 中

    public function index()
{
    $data = array(
        'title' =>'Customize',
        'heading' =>'List',
        'customize' => Customize::where(['user_id' => Auth::user()->id])->first(),
    );
    if ($data['customize'])
    {
        return redirect()->route('customize.edit', ['locale' => app()->getLocale(), 'customize' => $data['customize']]); // Redirect to Edit Route If Language available in DB
    }
    return view('Customize.index')->with($data);
}

route:list 命令O/P如下:

GET|HEAD  | {locale}/customize/{customize}/edit | customize.edit | App\Http\Controllers\CustomizeController@edit | web,setlocale,auth

甚至尝试从刀片硬编码为:

<a href="{{ url(app()->getLocale().'/customize/1/edit') }}">
        <button type="button" class="btn btn-warning">Edit</button>
    </a>

完成项目available here

【问题讨论】:

    标签: php laravel laravel-routing laravel-5.8


    【解决方案1】:

    错误非常简单。

    edit 方法使用路由参数调用,后跟您定义的从容器中获取的对象。

    由于您将 customize 参数传递给路由,因此您的方法参数应该定义如下:

    public function edit(string $customize, App\Model\Customize $customizeModel)
    {
        $customizeModel
            ->whereUserId(Auth::user()->id)
            ->update(['customize' => $customize]);
    
        $return response(); // whatever you need
    }
    

    【讨论】:

    • 现在我必须修改我的控制器,例如 public function edit($locale, Customize $customize)public function update($locale, Request $request, Customize $customize)。是否可以在某处全局进行此更改,而不是在每个控制器中进行更改???????????????无论如何,它按预期工作!谢谢!
    猜你喜欢
    • 2019-01-28
    • 1970-01-01
    • 2020-11-26
    • 2020-11-17
    • 2014-12-21
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多