简体   繁体   中英

Laravel REST API when to create separate controllers for list of values?

Let's say I have a simple API for registering a user. For each user I collect basic information such as: Name, email, state, gender, marital status. For state, gender and marital status I have a database table pre-populated with ids so I can present them in a dropdown and have the user select each.

Now when it comes to my API controller for registering users, should I be passing the list of values in a single JSON object?

return response()->json([
    'genderList' => Gender::get('id', 'name'),
    'stateList'  => State::get('id', 'abbr'),
    'maritalList => MaritalStatus::get('id', 'name')
]);

Or should I have a separate controller and API call for each of these that each return a single object?

Is there a proper way to do this or is it personal preference?

I'm using Vue as my frontend if that matters.

It is indeed a personal preference as there is no proper way of doing it. Keep in mind the number of network calls that will be passed and the number of hits on your database.

Personally, I prefer outputting an array using the pluck() method:

return response()->json([
    'genderList' => Gender::pluck('name', 'id'),
    'stateList'  => State::pluck('abbr', 'id'),
    'maritalList => MaritalStatus::pluck('name', 'id')
]);

It would be good as well to Cache those results as they may not change this often

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM