Laravel Controllers

In MVC frameworks controller are used to handle the route request and the forward to corresponding model class. By the same means laravel controllers may also have multiple functions that can perform different actions.

Controller classes are created in App/Http/Controllers folder by default. All application controllers are extended from controller class. We can create controller classes using the following artisan command.

php artisan make:controller Controller_Name

Controller name is written in camel case.

Laravel Resource Controller

Resource controller is special type of controller that have predefined CRUD functions. We just have to write logic implementation in these methods. Resource controller are also very convenient to access from route file. We can write single route for accessing all defined methods in controller. These methods are included in resource controller.

  1. index
  2. create
  3. show
  4. edit
  5. update
  6. destroy

Resource Controller Example

php artisan make:controller HomeController -r

How Resource Controller Methods Called

In laravel the default controller methods are provided in above list are associated with different HTTP verbs. Each method is called when a particular URI and HTTP verb is matched. If we have resource HomeController the its methods will be called as.

HTTP Verb URI Method Route
get /HomeController index my.index
get /HomeController/create create HomeController.create
post /HomeController store HomeController.store
get /HomeController/{id} show HomeController.show
get /HomeController/{id}/edit edit HomeController.edit
put/patch /HomeController/{id} update HomeController.update
delete /HomeController/{id} destroy HomeController.destroy

We just have to use -r flag while creating controller using php artisan.

Create Single Action Controller

Beside this controller can have multiple user defined or resource methods, we can also create a controller in laravel that has only one method. In route file only name of this controller. __invoke is the only one method written in single method controller.

Syntax

The default invoke function of invokabe controller in laravel is as:

public function __invoke()
    {
        // some lines of code
    }

Create invokable Controller

Using artisan command we have to write --invokable flag in laravel.

php artisan make:controller HomeController --invokable

Use Middleware with controller

We can assign particular middleware to all or partial methods from th controller class. For this purpose we can assign middleware in controller construct method. Other than this if we want to assign middleware to only particular method of controller then this will only specified in route that is calling controller function.

class HomeController extends Controller {
   public function __construct() {
      $this->middleware('primary_check');
   }
}

 

Comments
Login to TRACK of Comments.