I'm trying to update a user.
Here is my model:
<?php
namespace App\Models;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'user_type',
'username'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Here is the update controller:
public function update(Request $request, User $user)
{
$user->update($request->all());
return response()->json($user, 200);
}
Here is the api.php:
Route::group([
'prefix' => 'users',
'middleware' => ['cors', 'json.response', 'auth:api']
], function () {
Route::put('/{user}', [UserController::class, 'update']);
});
I'm sending request with VSCode extension like this:
PUT {{server}}/users/2
Content-Type: application/json
Authorization: Bearer {{token}}
{
"name": "Jane Doe",
}
But it's not changing the name
. I couldn't understand what am I missing.
I have tried to change the selecting User data on my own. But not working.
I think it's about not extending use Illuminate\Database\Eloquent\Model;
.
CodePudding user response:
Probably controller can't find $user. Change your code to $user = auth('api')->user(); in update function. And delete User $user from brackets.
CodePudding user response:
Check all your existing routes with php artisan route:list
. You'll notice that your route is just a wildcard.
Update your route to look like this:
Route::put('users/{user}', [UserController::class, 'update']);