Skip to main content

Documentation Index

Fetch the complete documentation index at: https://kawax.biz/llms.txt

Use this file to discover all available pages before exploring further.

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:
Route::get('/', function () {
    return 'Hello World';
});

Returning an array

Return an array and Laravel automatically converts it to a JSON response:
Route::get('/users', function () {
    return [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob'],
    ];
});
Returning an Eloquent model or collection also produces a JSON response automatically — a convenient pattern for building simple APIs.

Returning an Eloquent model

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:
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

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

Returning a view

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

namespace App\Http\Controllers;

use Illuminate\View\View;

class HomeController extends Controller
{
    public function index(): View
    {
        $users = [
            ['name' => 'Alice', 'email' => '[email protected]'],
            ['name' => 'Bob', 'email' => '[email protected]'],
        ];

        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.
Adding the Illuminate\View\View return type hint makes the intent of your method immediately clear.

Controlling status code and headers alongside a view

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:
use Illuminate\Http\RedirectResponse;

Route::get('/old-page', function (): RedirectResponse {
    return redirect('/new-page');
});
Controller example:
<?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:
// Defining named routes
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
// 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:
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:
return redirect('/posts')->with('success', 'Post created successfully.');
Display the message in a Blade template:
@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:
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:
return response()->json(['message' => 'Created'], 201);
Controller example:
<?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);
    }
}
Returning an array or Eloquent model directly also produces JSON, but response()->json() gives you fine-grained control over status codes and headers.

Response headers

Add headers with the header() method:
return response('Hello World')
    ->header('Content-Type', 'text/plain')
    ->header('X-Custom-Header', 'MyValue');
Set multiple headers at once with withHeaders():
return response('Hello World')
    ->withHeaders([
        'Content-Type' => 'text/plain',
        'X-Custom-Header' => 'MyValue',
        'Cache-Control' => 'no-cache',
    ]);

Example: a complete resource controller

1

Define the routes

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');
2

Implement the controller

<?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.');
    }
}
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.

Next steps

Session

Learn how to store data across requests using Laravel’s session.
Last modified on March 29, 2026