Laravel/PHP如何从Request中获取对象值?Offer存储接口疑问
Hey there! Let's walk through how to grab values from your object-formatted API request in Laravel's OffersController@store method.
Basic Top-Level Properties
First off, if your API sends a flat JSON object like this:
{ "title": "Senior Developer Role", "body": "Full-time remote position", "region": "Europe", "specialities": [2, 4] }
Your current code actually works perfectly! Laravel automatically parses JSON request bodies (when the Content-Type header is set to application/json) into the Request instance. So using $request->title, $request->body, etc., is totally valid. For consistency, you can also use the input() method:
$offer->title = $request->input('title');
Both approaches will give you the same value.
Handling Nested Objects
If your request sends a nested object (like wrapping the offer data inside a parent key), for example:
{ "offer_data": { "title": "Senior Developer Role", "body": "Full-time remote position", "region": "Europe" }, "specialities": [2, 4] }
You'll need to adjust how you access the values. Two easy ways to do this:
- Array-style access on the nested property:
$offer->title = $request->offer_data['title']; - Using dot notation with the
input()method:$offer->title = $request->input('offer_data.title');
Pro Tip: Add Request Validation
To make your code more robust and ensure you're receiving valid data, add validation at the start of your store method. This also gives you a validated array of data to work with, which is safer:
public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|string|max:255', 'body' => 'required|string', 'region' => 'required|string', 'specialities' => 'required|array|exists:specialities,id', // Ensures speciality IDs exist in your database ]); $offer = new Offer; $offer->title = $validated['title']; $offer->body = $validated['body']; $offer->region = $validated['region']; $offer->user_id = auth()->user()->id; $offer->save(); $offer->specialities()->sync($validated['specialities'], false); return response()->json([ 'created' => true ], 201); }
Troubleshooting: Verify Request Parsing
If you're still having trouble accessing values, dump the full request data to check what Laravel is parsing:
// Add this at the start of your store method dd($request->all());
This will show you all parsed parameters, so you can confirm your property names match exactly (remember: JSON keys are case-sensitive!).
内容的提问来源于stack exchange,提问作者gileneusz

