Laravel Controllers




Introduction to Laravel Controllers

Preferably of determining all of your request administration or handling logic as Closures in route files, you may prefer to build this action applying or using Controller classes. Controllers can group associated request handling logic within a single category or class. Controllers are saved or stored in the app/Http/Controllers of laravel controller constructor directory.

In the MVC framework, the character ‘C’ stands for Controller. It operates as governing traffic connecting Views and Models. In this chapter, you will discover and learn in depth about Controllers in Laravel.

Basic Controllers

Creating Controllers

Initiate the command prompt or terminal based on the working system you are utilising and type the following command to generate or create a controller applying the Artisan CLI (Command Line Interface).

 

php artisan make:controller <controller-name> –plain

You can now replace the <controller-name> with the name of your desired controller, will produce a plain constructor as we are transferring or passing the argument — plain. If you don’t require to generate a plain constructor, you can neglect the argument. The created constructor can be viewed at app/Http/Controllers.

 

You can append your custom coding as you will see the basic coding has already been done for you. The generated controller may be called from routes.php by the following syntax. The example given below is a basic controller class. Perceive that the laravel controller constructor elongates the base controller class involved with Laravel. The base class implements a few convenience systems or method such as the middleware method, which can be applied to append middleware to controller operations:

 

Syntax

You can determine a route to this controller action like so:

 

Route::get(‘user/{id}’, ‘UserController@show’);

Promptly, when a provided request meets the particularised route URI, the show method on the UserController class will be administered. Also, it is obvious that the route parameters will also be declared and passed to the method.

 

Controllers & Namespaces

The most significant thing in laravel controller creation to note is that we did not require to define the full controller namespace when determining the controller route. Considering the RouteServiceProvider loads your route data files inside or within a route group that comprises the namespace, we only specified the part of the class name that appears after the App\Http\Controllers division of the namespace.

 

If you prefer to nest your controllers deep-toned into the App\Http\Controllers record directory, apply the particular class name corresponding to the App\Http\Controllers root namespace. So, if your full controller class is App\Http\Controllers\Images\AdminController, you should register routes to the controller like so:

 

Route::get(‘foo’, ‘Photos\AdminController@method’);

 

 

If you would wish to assign or define a controller that only manipulates or handle a single operation, you may put or place a unique or a single__invoke method on the controller:

When enrolling routes for eligible as well as single action controllers, you do not require to define a method:

 

Route::get(‘user/{id}’, ‘ShowProfile’);

 

You can produce an invokable controller by utilising the –invokable selection of the  make:controller Artisan command:

 

php artisan make:controller ShowProfile –invokable

 

Controller Middleware

We have seen middleware already. Furthermore, it can be applied with controller also. Middleware may be assigned to the controller’s routes in your route files:

 

Route::get(‘profile’, ‘UserController@show’)->middleware(‘auth’);

Though, it is further advantageous to designate middleware within your controller’s constructor. Applying the middleware method from your controller’s laravel controller constructor, you may readily specify middleware to the controller’s operation. You can indeed limit the middleware to particularly certain methods on the controller class:

Controllers further authorise you to enrol middleware utilising a Closure which implements a convenient means to describe a middleware for a single controller externally determining a whole middleware class:

Resource Controllers

laravel controller tutorial will lead to having an in-depth knowledge about the resource controllers. Laravel resource routing specifies or assigns the typical “CRUD” routes to a controller including a single line of code. For instance, you may crave to build or create a controller that controls all HTTP requests for “photos” cached by your application. Utilising the make:controller Artisan command, we may promptly create such a controller:

 

php artisan make:controller PhotoController –resource

This command as mentioned earlier will help to generate a controller at app/Http/Controllers/PhotoController.php. The controller will comprise a method for each of the accessible resource operations.

 

Ensuing, you can record an original and resourceful route to the controller:

Route::resource(‘photos’, ‘PhotoController’);

 

This particular, as well as single route declaration, produces various routes to manipulate or handle a variety of activities on the resource.

 

You can register multiple resource controllers at once by declaring an array to the resources method:

Specifying The Resource Model



If you are using laravel controller creation method also utilising route model merging and would desire the resource controller’s methods to type-hint a model instance, you can utilise the –model option when creating the controller:

 

php artisan make:controller PhotoController –resource –model=Photo

 

Spoofing Form Methods

As HTML forms can’t make PUT, PATCH, or DELETE requests, you will require to attach a hidden _method field to spoof these HTTP verbs. The @method Blade directive can produce this track for you:

Partial Resource Routes

When representing a resource route, you may define a subset of operations the controller should manage rather of the complete assortment of default actions:

API Resource Routes

API Resource Routes consumes the resource routes thus when representing resource routes that will be consumed by APIs; you will generally need to eliminate routes that impersonate HTML templates such as create and edit. For support, you may apply the apiResource method to exclude these two routes automatically:

 

Route::apiResource(‘photos’, ‘PhotoController’);

 

You may designate multiple API resource controllers at once via enacting an array to the  apiResources method:

To rapidly create an API resource controller laravel controller constructor that does not involves the create or edit methods, you should use the –api switch when establishing or executing the make:controller command:

 

php artisan make:controller API/PhotoController –api

 

Naming Resource Routes

All resource controller operations or action have a route name by default; though, you are allowed to override these names by giving or passing a names array with your options:

Naming Resource Route Parameters

Route::resource will generate by default the route parameters for your resource routes based on the “singularized” variant or version of the resource name. You can revoke this on a per-resource base by utilising the parameters method. The array carried into the parameters of laravel controller origination method should be an associative array of resource names and parameter names:

The example above produces the subsequent URIs for the resource’s show route:

/users/{admin_user}

Localizing Resource URIs

By default, Route::resource will generate resource URIs applying English verbs. If you want to confine the create and edit act verbs, you can utilise the Route::resourceVerbs method. It can be served in the boot program of your AppServiceProvider:

Once the verbs have been customised, a resource route enrolment such as  Route::resource(‘photos’, ‘PhotoController’) will provide the following URIs:

/photos/clear

/photos/{photo}/editar

 

Supplementing Resource Controllers

If you want to append additional routes to laravel controller creation and a resource controller exceeding the default inclination of resource routes, you should determine those routes before your call to Route::resource; otherwise, the routes specified by the resource method may involuntarily take priority superior your supplemental routes:

Route::get(‘photos/popular’, ‘PhotoController@method’);

Route::resource(‘photos’, ‘PhotoController’);

 

Dependency Injection & Controllers

 

Constructor Injection

The Laravel service package or a container is used to solve all Laravel controllers. As a conclusion, you can touch-type-hint any provinces your controller may demand in its constructor. The stated provinces or dependencies will automatically be solved and inserted into the controller instance:

It is apparent that you may also type-hint any Laravel contract. If the package or container can resolve it, you can type-hint it. Depending on your application, inserting your dependencies within your controller may render greater testability.

 

Method Injection

In extension to laravel controller constructor injection, you may also type-hint dependencies on your controller’s methods. A typical use-case for custom or method injection is inserting or injecting the Illuminate\Http\Request instance in your controller methods:

If your controller method is further demanding input from a route parameter, list your program route arguments after your different other dependencies. For instance, if your route is determined or defined like so:

 

Route::put(‘user/{id}’, ‘UserController@update’);

 

You can yet type-hint the Illuminate\Http\Request and locate your id parameter by determining your controller method as follows:

 

Route Caching

laravel controller tutorial has a high-grade learning directory, and If your application is particularly using controller based routes, you should grasp the comfort of Laravel’s route cache. Appropriating the route cache will drastically shorten the measure of the time it necessitates to register all of your application’s routes. In some different quandaries, your route registration may indeed be up to 100x quicker. To create a route cache, accomplish the route:cache Artisan command:

 

php artisan route:cache

After operating or executing this command, your cached routes file will be placed and loaded on every request regarding the laravel controller constructor. Acknowledge, if you append some distinct routes, you will require to produce a current route cache. Because of this, you should exclusively operate the route:cache command throughout your project’s deployment.

 

You may apply the route:clear command to remove the route cache: