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

> Learn how to create Laravel controllers and how they integrate with routing.

## What are controllers

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

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

## Creating a controller

To quickly generate a new controller, use the `make:controller` Artisan command.
By default, all of the controllers for your application are stored in the `app/Http/Controllers` directory.

```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 a controller class and method, you may define a route to the controller method like so:

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

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

When an incoming request matches the specified route URI, the `show` method on the `App\Http\Controllers\UserController` class will be invoked and the route parameter will be passed to the method.

<Info>
  Controllers are not required to extend a base class. However, it is sometimes convenient to extend a base controller class that contains methods that should be shared across all of your controllers.
</Info>

## Single action controllers

If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action.
To accomplish this, define a single `__invoke` method within the controller.

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

namespace App\Http\Controllers;

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

When registering routes for single action controllers, you do not need to specify a controller method.
Simply pass the name of the controller to the router.

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

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

You may generate an invokable controller by using the `--invokable` option on the `make:controller` Artisan command.

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

## Resource controllers

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

You may use the `--resource` option on the `make:controller` Artisan command to quickly create a controller to handle these actions.

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

This command generates a controller at `app/Http/Controllers/PhotoController.php`.
The controller contains a method stub for each of the available resource operations.
Next, register a resource route that points to the controller.

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

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

This single route declaration creates multiple routes to handle a variety of actions on the resource.
The generated controller already has methods stubbed for each of these actions.

| HTTP method | 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>
  Running `php artisan route:list` provides a quick overview of your application's routes.
</Info>

### Partial resource routes

When declaring a resource route, you may 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 that will be consumed by APIs, you commonly want to exclude routes that present HTML templates, such as `create` and `edit`.
The `apiResource` method automatically excludes these two routes.

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

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

## Dependency injection

### Constructor injection

The Laravel service container is used to resolve all Laravel controllers.
As a result, you are able to type-hint any dependencies your controller may need in its constructor.
The declared dependencies will automatically be resolved and injected into the controller instance.

```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 may also type-hint dependencies on your controller's methods.
A common use case for method injection is injecting the `Illuminate\Http\Request` instance into your controller methods.

```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;

        // Save the user...

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

If your controller method also receives input from a route parameter, list your route arguments after your other dependencies.
For example, if your route is defined as follows:

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

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

You can define the controller method so that it type-hints the `Illuminate\Http\Request` and accesses the `id` parameter like so:

```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>
  Making the most of dependency injection makes it easier to swap in mocks during testing, improving the testability of your code.
</Tip>

## Next steps

<Card title="Routing" icon="route" href="/en/routing">
  Review how to define routes and integrate them with controllers.
</Card>


## Related topics

- [Routing](/en/routing.md)
- [Controller PHP Attributes](/en/advanced/controller-attributes.md)
- [Laravel 11+ New Application Structure FAQ](/en/advanced/app-structure-faq.md)
- [URL generation](/en/urls.md)
- [Introducing Laravel Wayfinder](/en/blog/wayfinder-introduction.md)
