0

Using the following route declaration, I am trying to pass a parameter to the controller method however I am unsure of how to do this. I don't want a route parameter but instead a hard coded parameter so that I can use the same function for both updating the current user and other users using a parameter to distinguish between the two operations.

Route::patch('/v1/user', [UserController::class, 'update']);

I need to pass a boolean value to the update method from this Route statement, any ideas?

4
  • how are you accessing your API? meaning what is your frontend language? you can attach variables with your requests which you can read in your Laravel Controller. Commented Jun 22, 2021 at 17:49
  • Yes I could do that however I would prefer to have separate routes. /api/v1/user to update the current user and /api/v1/user/{id} to update a specific user ID, but I want to use the same controller method to achieve this, with a variable to inform the controller method which route is calling the method. Commented Jun 22, 2021 at 17:53
  • 1
    Then you want an Optional Query Parameter: Route::patch('/v1/user/{id?}', ...); id can be included or excluded, and you can hook into that in the Controller method and act accordingly. Commented Jun 22, 2021 at 17:59
  • 1
    Thank you @TimLewis, exactly what I was after. Commented Jun 22, 2021 at 18:03

2 Answers 2

1

There are two simple ways to do this

  1. A general method to update the user
public function updateUser($user){...}

Then you can just call this function from the other controllers. This way, your code becomes flexible and easier to test/mock

  1. Make $id as nullable
public function update($id = null)
{
    if($id) {
        $user = User::find($id);
    } else {
        $user = auth()->user();
    }
    // Update user
}
Sign up to request clarification or add additional context in comments.

Comments

0

Do not you mean this?
Route::patch('/v1/user/{id}', [UserController::class, 'update']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.