简体   繁体   中英

Error trying to edit a user on Laravel 5.4

I'm starting a project with laravel, and I'm having a problem when I try to edit a user.

It always return the "QueryException" as if I didn't pass the user ID, but I used the default layout for my Model, so my URL is something like /users/1/edit.

QueryException错误

This is how my route is defined:

Route::get('/', function(){
    return view('welcome');
});

Route::resource('users', 'CtrUsers');

This is the way I get the edit URL:

href="{{route('users.edit', $user)}}"

(the $user is set inside a foreach loop)

And this is my edit function:

public function edit(User $user)
{
    return view('users.edit', compact('user'));
}

And something strange is that when I enter the URL /users/edit/1 (with de ID in the end), IT stops returning the QueryException, but returns "NotFoundHttpException".

NotFoundHttpException

Anyone had this problem?

change your controller

public function edit($id)
{
    $user = User::findOrFail($id);
    return view('users.edit', compact('user'));
}

Edited again

 public function edit($id)
    {
        $user = User::where('usr_id',$id)->findOrFail();
        return view('users.edit', compact('user'));
    }

The issue is with the variable name which you have used for route model binding. Both variable names: the one which is on the route and another from the action parameter must match.

You can check the route info using php artisan route:list command.

So you have two options, either change the users variable name to user in the route like:

Route::resource('user', 'CtrUsers');

OR

You can change the variable name from user to users in the action parameter like:

public function edit(User $users)
{
    return view('users.edit', compact('user'));
}

For more info:

https://laravel.com/docs/master/routing#route-model-binding

我发现最好的解决方案是重建迁移,将表ID的名称更改为“ ID”,因为我注意到错误始终存在,因为系统找不到任何名为usr_id的列。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM