🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Responses

A response is what Laravel sends back to the browser. Every route ends by returning a response.

Return a plain string

A route can return a short string.

return 'Hello from Laravel';

Build a response

The response helper sets the body and the status.

return response('Hello from Laravel', 200);

Set a created status

A 201 status says a new item was created.

return response('Created', 201);

Add a header

The header method adds one header to the reply.

return response('Hello from Laravel', 200)
    ->header('X-Greeting', 'hello');

Example

Route::get('/l21/hello', function () {
    return response('Hello from Laravel', 200);
});

Key points

  • Use response() when the reply needs more than a plain string.
  • Use a plain string return for a short text reply.
  • Use a status code to say what happened, such as 200 for success.
  • Use the header method to add an extra header to a reply.

In this example, the route handles /l21/hello. It calls response() with the text Hello from Laravel. It sets the status to 200. A response is what Laravel sends back to the browser.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does response('Hello', 200) return?