Skip to content

Request handling & responses

Marco E edited this page Sep 7, 2020 · 5 revisions

HTTP Requests

  • When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig into JSON arrays:
$name = $request->input('user.name');

HTTP Responses

  • The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:
return response()->json([
    'name' => 'Abigail',
    'state' => 'CA',
]);

return response()->json([
    'msg' => 'post created',
    'post' => [
        'title' => $post->$title
    ]
], 200);

Validation

  • To validate data, use the validate method provided by the Illuminate\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',
]);
Clone this wiki locally