Home > database >  how to make a update api in laravel using autherntication token
how to make a update api in laravel using autherntication token

Time:12-26

i am trying to make a update API that updates fileds using header auth token

I am new to larvel

this is what I have tried

Route::patch('/update', function (\Illuminate\Http\Request $request) {
  
    $data = $request->validate([
        'name' => '|max:255',
        'phone'=> 'max:255',
        'email' => '|email|unique:users',
          'period'=> 'max:255',
            'babyname'=> 'max:255',
              'baby_date'=> 'max:255',
        
            
      
    ])}) return new \Illuminate\Http\JsonResponse(['user' => $user] , 200);
})->middleware('auth:api');

enter image description here

CodePudding user response:

Few recommendations:

  1. Use resource route instead of single routes -> https://laravel.com/docs/9.x/controllers#resource-controllers

  2. Read more about validation rules -> https://laravel.com/docs/9.x/validation#available-validation-rules

  3. You can customize the response status:

    200 Success
    404 Not Found (page or other resource doesn't exist)
    401 Not authorized (not logged in)
    403 Logged in but access to requested area is forbidden
    400 Bad request (something wrong with URL or parameters)
    422 Unprocessable Entity (validation failed)
    500 General server error
    

API Route

//In the api route header
use App\Http\Controllers\UserController;
 
//The route method
Route::patch('/update/{user}', [UserController::class, 'update'])->middleware('auth:api');

UserController

    /**
     * Update the specified model.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  User $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //Please read: https://laravel.com/docs/9.x/validation#available-validation-rules
        //For more information about validation rules and how they work.
        $data = $request->validate([
                    'name' => '|max:255',
                    'phone'=> 'max:255',
                    'email' => '|email|unique:users',
                    'period'=> 'max:255',
                    'babyname'=> 'max:255',
                    'baby_date'=> 'max:255',
                ]);
                
        $user->update($data);
        
        //You can pass a response status to handle it in your view/javascript as required 
        return response()->json([
            'user' => $user->toArray(),
        ], 200);
    }

Please let me know if you require further help or clarifications, always happy to help.

CodePudding user response:

Fix your route; it is not found; you have to supply the ID inside the route to reach the controller:

Route::patch('/update/{id}', function (\Illuminate\Http\Request $request) {
// ...
  • Related