> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Responses

> Return views, redirects, JSON, and more from Laravel controllers and routes.

## Overview

Every route or controller action must return a response to the user's browser. Laravel makes it easy to return strings, arrays, views, redirects, and JSON — all with minimal code.

## Basic responses

### Returning a string

The simplest response is a plain string. Laravel automatically converts it into a proper HTTP response:

```php theme={null}
Route::get('/', function () {
    return 'Hello World';
});
```

### Returning an array

Return an array and Laravel automatically converts it to a JSON response:

```php theme={null}
Route::get('/users', function () {
    return [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob'],
    ];
});
```

<Info>
  Returning an Eloquent model or collection also produces a JSON response automatically — a convenient pattern for building simple APIs.
</Info>

### Returning an Eloquent model

```php theme={null}
use App\Models\User;

Route::get('/user/{user}', function (User $user) {
    return $user;
});
```

## The Response object

Use the `response()` helper when you need to control the HTTP status code or headers:

```php theme={null}
Route::get('/home', function () {
    return response('Hello World', 200)
        ->header('Content-Type', 'text/plain');
});
```

The first argument is the response body; the second is the HTTP status code.

### Common HTTP status codes

| Code  | Meaning                                 |
| ----- | --------------------------------------- |
| `200` | OK                                      |
| `201` | Created                                 |
| `204` | No Content                              |
| `301` | Moved Permanently                       |
| `302` | Found (temporary redirect)              |
| `404` | Not Found                               |
| `422` | Unprocessable Entity (validation error) |
| `500` | Internal Server Error                   |

## Returning a view

Use `view()` to render a Blade template. This is the most common response in a web application:

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\View\View;

class HomeController extends Controller
{
    public function index(): View
    {
        $users = [
            ['name' => 'Alice', 'email' => 'alice@example.com'],
            ['name' => 'Bob', 'email' => 'bob@example.com'],
        ];

        return view('users.index', ['users' => $users]);
    }
}
```

The first argument is the view name; the second is an array of data to pass to the template.

<Tip>
  Adding the `Illuminate\View\View` return type hint makes the intent of your method immediately clear.
</Tip>

### Controlling status code and headers alongside a view

```php theme={null}
return response()
    ->view('errors.404', ['message' => 'Page not found'], 404);
```

## Redirects

### Basic redirect

The `redirect()` helper returns a redirect response. It's commonly used after form submissions to send users to a different page:

```php theme={null}
use Illuminate\Http\RedirectResponse;

Route::get('/old-page', function (): RedirectResponse {
    return redirect('/new-page');
});
```

Controller example:

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        // Save the post...

        return redirect('/posts');
    }
}
```

### Redirecting to a named route

Use the `route()` helper to redirect by route name instead of a hard-coded URL. If the URL ever changes, you only need to update the route definition:

```php theme={null}
// Defining named routes
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
```

```php theme={null}
// Redirect to a named route
return redirect()->route('posts.index');

// With route parameters
return redirect()->route('posts.show', ['post' => $post->id]);
```

### Redirecting back

Use `back()` to redirect to the user's previous location. This is common after a validation failure:

```php theme={null}
return back();

// Preserve the previous input so forms can be repopulated
return back()->withInput();
```

### Redirect with a flash message

Use `with()` to store a message in the session for the next request:

```php theme={null}
return redirect('/posts')->with('success', 'Post created successfully.');
```

Display the message in a Blade template:

```blade theme={null}
@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
```

## JSON responses

For APIs, return JSON explicitly with `response()->json()`. Laravel sets the `Content-Type: application/json` header automatically:

```php theme={null}
use Illuminate\Http\JsonResponse;

Route::get('/api/users', function (): JsonResponse {
    $users = [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob'],
    ];

    return response()->json($users);
});
```

Include a status code:

```php theme={null}
return response()->json(['message' => 'Created'], 201);
```

Controller example:

```php theme={null}
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(User::all());
    }

    public function store(Request $request): JsonResponse
    {
        $user = User::create($request->validated());

        return response()->json($user, 201);
    }
}
```

<Info>
  Returning an array or Eloquent model directly also produces JSON, but `response()->json()` gives you fine-grained control over status codes and headers.
</Info>

## Response headers

Add headers with the `header()` method:

```php theme={null}
return response('Hello World')
    ->header('Content-Type', 'text/plain')
    ->header('X-Custom-Header', 'MyValue');
```

Set multiple headers at once with `withHeaders()`:

```php theme={null}
return response('Hello World')
    ->withHeaders([
        'Content-Type' => 'text/plain',
        'X-Custom-Header' => 'MyValue',
        'Cache-Control' => 'no-cache',
    ]);
```

## Example: a complete resource controller

<Steps>
  <Step title="Define the routes">
    ```php theme={null}
    use App\Http\Controllers\PostController;

    Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
    Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
    Route::post('/posts', [PostController::class, 'store'])->name('posts.store');
    Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
    Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy');
    ```
  </Step>

  <Step title="Implement the controller">
    ```php theme={null}
    <?php

    namespace App\Http\Controllers;

    use App\Models\Post;
    use Illuminate\Http\RedirectResponse;
    use Illuminate\Http\Request;
    use Illuminate\View\View;

    class PostController extends Controller
    {
        // Return a view for listing posts
        public function index(): View
        {
            $posts = Post::latest()->get();

            return view('posts.index', ['posts' => $posts]);
        }

        // Return a view for the creation form
        public function create(): View
        {
            return view('posts.create');
        }

        // Save and redirect
        public function store(Request $request): RedirectResponse
        {
            $post = Post::create($request->validated());

            return redirect()
                ->route('posts.show', ['post' => $post->id])
                ->with('success', 'Post created successfully.');
        }

        // Return a view for a single post
        public function show(Post $post): View
        {
            return view('posts.show', ['post' => $post]);
        }

        // Delete and redirect
        public function destroy(Post $post): RedirectResponse
        {
            $post->delete();

            return redirect()
                ->route('posts.index')
                ->with('success', 'Post deleted.');
        }
    }
    ```
  </Step>
</Steps>

<Tip>
  In web applications, display actions return a `View` and mutating actions (create, update, delete) redirect after completing. This pattern prevents duplicate form submissions on refresh.
</Tip>

## Next steps

<Card title="Session" icon="database" href="/en/session">
  Learn how to store data across requests using Laravel's session.
</Card>


## Related topics

- [VoicevoxResponse - VOICEVOX for Laravel](/en/packages/laravel-voicevox/response.md)
- [Request Lifecycle](/en/lifecycle.md)
- [Rate Limiting](/en/advanced/rate-limiting.md)
- [Core package and custom drivers - Feedable](/en/packages/feedable/core.md)
- [Laravel MCP](/en/mcp.md)
