-
Notifications
You must be signed in to change notification settings - Fork 0
Request handling & responses
Marco E edited this page Sep 7, 2020
·
5 revisions
- When sending JSON requests to your application, you may access the JSON data via the
input
method as long as theContent-Type
header of the request is properly set toapplication/json
. You may even use "dot" syntax to dig into JSON arrays:
$name = $request->input('user.name');
- For more info, see requests.
- The
json
method will automatically set theContent-Type
header toapplication/json
, as well as convert the given array to JSON using thejson_encode
PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA',
]);
return response()->json([
'msg' => 'post created',
'post' => [
'title' => $post->$title
]
], 200);
- For more info, see responses.
- To validate data, use the
validate
method provided by theIlluminate\Http\Request
object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
- Alternatively, validation rules may be specified as arrays of rules instead of a single
|
delimited string:
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
- If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
- For more info, see validation
meeting-API - 2020