skip to Main Content

I using API resources with nested controllers, my urls look like:

GET /api/projects
POST /api/projects
...
GET /api/projects/:uuid/employees
POST /api/projects/:uuid/employees

I using also Request to save data per endpoint (for validation too).

The question is how to post data to save new employee (name, email, etc.) and validate and save value for project_id from URL?

Request rules:

public function rules(): array
{
    return [
        'project_id' => ['required'],
        'name' => ['required', 'max:30'],
        'email' => ...,
    ];
}

My posted data has just name and email values and I would like get/set value for project_id from URL, it is possible?

2

Answers


  1. You can use prepareForValidation

    protected function prepareForValidation() {
      return $this->merge([
        'project_id' => request()->route('uuid'), 
      ]);
    }
    
    Login or Signup to reply.
  2. Yes, you can merge or add project_id to an existing request.

      $project_id = $request->route('project_id');
      //Add to request
      $request->request->add(['project_id' => $project_id]);
      //OR
      $request->merge(['project_id' => $project_id])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search