skip to Main Content

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 (IlluminateHttpRequest $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 IlluminateHttpJsonResponse(['user' => $user] , 200);
})->middleware('auth:api');

enter image description here

enter image description here

3

Answers


  1. 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 AppHttpControllersUserController;
     
    //The route method
    Route::patch('/update/{user}', [UserController::class, 'update'])->middleware('auth:api');
    

    UserController

        /**
         * Update the specified model.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  User $user
         * @return IlluminateHttpResponse
         */
        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.

    Login or Signup to reply.
  2. 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 (IlluminateHttpRequest $request) {
    // ...
    
    Login or Signup to reply.
  3. Changes

    1. Removed typo. 'name' => '|max:255' to 'name' => 'max:255' and 'email' => '|email|unique:users' to 'email' => 'email|unique:users'
    2. Condition based unique() check added 'email|unique:users,email,' . $request->user()->id,. This will be used to Skip the Current record.
    3. return should be placed inside the Route(), not outside.
    4. Used $user = $request->user(); to update the record.

    Route::patch('/update', function (IlluminateHttpRequest $request) {
    
        $user = $request->user();
    
        $data = $request->validate([
            'name' => 'max:255', # remove "|"
            'phone'=> 'max:255',
            'email' => 'email|unique:users,email,' . $request->user()->id,  # remove "|"
            'period'=> 'max:255',
            'babyname'=> 'max:255',
            'baby_date'=> 'max:255',
        ]);
    
        $user->update($data);
    
        return new IlluminateHttpJsonResponse(['user' => $user] , 200);
    })->middleware('auth:api');
    

    Or for the in-detail update.(Without update())

    $user = $request->user();
    
    $user->name = $data['name'];
    $user->phone = $data['phone'];
    $user->email = $data['email'];
    $user->period = $data['period'];
    $user->babyname = $data['babyname'];
    $user->baby_date = $data['baby_date'];
    
    $user->save();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search