Controllers group relate request handling logic into a single class. They are stored in the app/Http/Controllers directory.

Basic Controllers

Defining Controllers:

The controllers extend the base controller class included with Laravel.

The base class provides a few uses to obtain methods such as the middleware method, which we used to attach the middleware to controller actions:

We can easily define a route to this controller:

Now, when a request matches the specified route URI, the show method on the UserController class will be executed.

The route parameters will also be passed with this method.

  • Controllers are not required to extend a base class. On the other hand, we will not have access to convenience features such as the middleware, validate, and dispatch methods.

Controllers & Namespaces:

We did not need to specify the full controller namespace while defining the controller route.

The RouteServiceProvider loads our route files within a route group which contains the namespace, we can specify the portion of the class name that comes after the App\Http\Controllers portion of the namespace.

If we choose to divide our Controllers into the App\Http\Controllers directory, it uses the specific class name that is related to the App\Http\Controllers root namespace.

If our full controller class is App\Http\Controllers\Photos\AdminController, we should register routes to the controller like so:

Single Action Controllers:

If we would like to define a controller that are only handles a single action, we place a single _invoke method on the controller:

When we are registering routes for a single action controllers, we do not need to specify a method:

We can generate an invokable controller by using the –invokable option of the make:controller Artisian command:

php artisian make:controller ShowProfile –invokable

Pin It on Pinterest

Share This