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

# Controllers

> How to create controllers in Laravel and connect them to routes to organize your request handling logic.

## What is a controller?

Instead of defining all your request handling logic as closures in route files, you can organize this behavior using "controller" classes. Controllers group related request handling logic into a single class.

For example, a `UserController` class might handle all incoming requests related to users — displaying, creating, updating, and deleting them. By default, controllers are stored in the `app/Http/Controllers` directory.

## Creating a controller

Use the `make:controller` Artisan command to quickly generate a new controller:

```shell theme={null}
php artisan make:controller UserController
```

## Basic controllers

A controller class can have any number of public methods that respond to incoming HTTP requests:

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

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Show the profile for a given user.
     */
    public function show(string $id): View
    {
        return view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}
```

Once you have written the class and method, define a route pointing to it:

```php theme={null}
use App\Http\Controllers\UserController;

Route::get('/user/{id}', [UserController::class, 'show']);
```

When an incoming request matches the route URI, Laravel calls the `show` method on `UserController` and passes the route parameters to it.

<Info>
  Controllers do not need to extend a base class. However, extending a base controller class is useful when you want to share methods across all your controllers.
</Info>

## Single-action controllers

When a controller action is particularly complex, you may want to dedicate an entire controller class to that single action. To do so, define a single `__invoke` method inside the controller:

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

namespace App\Http\Controllers;

class ProvisionServer extends Controller
{
    /**
     * Provision a new web server.
     */
    public function __invoke()
    {
        // ...
    }
}
```

When registering a route for a single-action controller, you do not need to specify a controller method — pass the controller class name directly:

```php theme={null}
use App\Http\Controllers\ProvisionServer;

Route::post('/server', ProvisionServer::class);
```

Use the `--invokable` option to generate an invokable controller:

```shell theme={null}
php artisan make:controller ProvisionServer --invokable
```

## Resource controllers

Each Eloquent model in your application can be thought of as a "resource", and it is common to perform the same set of actions (CRUD) against each resource. Laravel's resource routing assigns typical create, read, update, and delete routes to a controller with a single line of code.

Use the `--resource` option to generate a controller with stub methods for each of the resource actions:

```shell theme={null}
php artisan make:controller PhotoController --resource
```

Then register a resource route pointing to the controller:

```php theme={null}
use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class);
```

This single declaration creates multiple routes to handle the various actions on the resource:

| HTTP verb | URI                    | Action  | Route name     |
| --------- | ---------------------- | ------- | -------------- |
| GET       | `/photos`              | index   | photos.index   |
| GET       | `/photos/create`       | create  | photos.create  |
| POST      | `/photos`              | store   | photos.store   |
| GET       | `/photos/{photo}`      | show    | photos.show    |
| GET       | `/photos/{photo}/edit` | edit    | photos.edit    |
| PUT/PATCH | `/photos/{photo}`      | update  | photos.update  |
| DELETE    | `/photos/{photo}`      | destroy | photos.destroy |

<Info>
  Run `php artisan route:list` to see an overview of all routes registered in your application.
</Info>

### Partial resource routes

When declaring a resource route, you can specify a subset of actions the controller should handle:

```php theme={null}
use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class)->only([
    'index', 'show'
]);

Route::resource('photos', PhotoController::class)->except([
    'create', 'store', 'update', 'destroy'
]);
```

### API resource routes

When declaring resource routes for an API, you typically want to exclude routes that present HTML templates, such as `create` and `edit`. Use `apiResource` to exclude both automatically:

```php theme={null}
use App\Http\Controllers\PhotoController;

Route::apiResource('photos', PhotoController::class);
```

## Dependency injection

### Constructor injection

Laravel's service container resolves all Laravel controllers. You can type-hint any dependencies your controller needs in its constructor, and they will be automatically resolved and injected:

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

namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected UserRepository $users,
    ) {}
}
```

### Method injection

In addition to constructor injection, you can type-hint dependencies on your controller methods. A common use case is injecting the `Illuminate\Http\Request` instance:

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

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Store a new user.
     */
    public function store(Request $request): RedirectResponse
    {
        $name = $request->name;

        // Store the user...

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

If your controller method also expects input from a route parameter, list your route arguments after your other dependencies:

```php theme={null}
use App\Http\Controllers\UserController;

Route::put('/user/{id}', [UserController::class, 'update']);
```

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

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Update the given user.
     */
    public function update(Request $request, string $id): RedirectResponse
    {
        // Update the user...

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

<Tip>
  Using dependency injection makes your controllers easier to test, because you can swap real implementations for mocks in tests.
</Tip>

## Next steps

<Card title="Routing" icon="arrow-right-arrow-left" href="/en/routing">
  Review how to define routes and connect them to controllers.
</Card>
