Controllers

In any of the MVC frameworks, ‘C’ is usually used to denote Controller. It helps in directing the traffic from views to models and vice versa.

Controller Creation

We will be creating the controller by using the Artisan CLI (Command Line Interface). To start with the process, first type in the mentioned command either on the command prompt (cmd) or on the terminal.

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

You need to replace the <controller-name> field with your desired controller name. As the argument passed in this command is plain, that’s why you will be able to create a plain constructor only. You can remove this argument if don’t want to create a plain constructor. This newly created controller is saved in the path app/Http/Controllers. Once you open the file, you will see an automated basic coding. To add in your own coding, you need to call this controller from the routes.php. Follow the given syntax.

Route::get(‘base URI’,’controller@method’);

For the better understanding of the syntax, you can take a look at the following example.

Step 2: Once the command executes successfully, you can find this newly created TestController at app/Http/Controller/TestController.php. The file will also contain the basic coding which will appear likewise the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class TestController extends Controller

{

//

}

[post_middile_section_ad]

Controller Middleware

We are already aware of the middleware which can be used with a controller too. In such a case, the middleware needs to be included in the controller’s constructor. In another way, a controller can enroute a middleware. It is not necessary that the middleware can access all the methods of the controller. The programmer can easily limit the access of a registered middleware.

Assignment of Middleware to Controller’s Route

In the below code, we are assigning the middleware to the TestController’s route.

Route::get(‘profile’, [

‘middleware’ => ‘auth’,

‘uses’ => ‘TestController@showProfile’

]);

Understand controller middleware with the given example.

Example

Step 1: Include the given code in the already existing file of routes.php. You can locate this file on the path: app/Http/routes.php.

<?php

Route::get(‘/testcontroller/path’,[

‘middleware’ => ‘First’,

‘uses’ => ‘TestController@showPath’

]);

Step 2: Create two new middleware with the name FirstMiddleware and SecondMiddleware.

laravel> php artisan make:middleware FirstMiddleware

laravel> php artisan make:middleware SecondMiddleware

Step 3: Now include the below written code in this newly created Middleware, which is FirstMiddleware.php. You can locate this file on the path: app/Http/Middleware.

<?php

namespace App\Http\Middleware;

use Closure;

class FirstMiddleware

{

public function handle($request, Closure $next)

{

echo ‘<br>First Middleware’;

return $next($request);

}

}

Add this following code to SecondMiddleware.php. You will get this file in the same directory of Middleware.

?php

namespace App\Http\Middleware;

use Closure;

class SecondMiddleware

{

public function handle($request, Closure $next)

{

echo ‘<br>Second Middleware’;

return $next($request);

}

}

Step 4: You will be required to create another controller under the name UserController. For the creation, you need to execute the following command.

laravel> php artisan make:controller UserController –plain

Step 5: After the successful creation of the UserController, add the below-mentioned command to the UserController.php file. You can find this file at app/Http/UserController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class UserController extends Controller

{

public function __construct()

{

$this->middleware(‘Second’);

}

public function showPath(Request $request)

{

$uri = $request->path();

echo ‘<br>URI: ‘.$uri;

$url = $request->url();

echo ‘<br>’;

echo ‘URL: ‘.$url;

$method = $request->method();

echo ‘<br>’;

echo ‘Method: ‘.$method;

}

}

Step 6: At this point, you have to launch the internal web server of PHP. To perform this, run the following command on the cmd or terminal.

laravel> php artisan serve

Step 7: Now enter the given URL on the recently launched PHP’s server.

Resource Controllers

Most of the time when we create an application, we go through a specific operation, which is CRUD (Create, Read, Update, Delete). But if you are using Laravel framework then more than half of your work is already done. You will be required to create the controller only and the rest of the methods will be provided to you automatically. You can have all these methods on the routes.php.

Go through this given example to understand resource controllers.

Step 1: Create a controller under the name TestController. To create this new controller, you need to execute the following command either at the command prompt (cmd) or at the terminal.

laravel> php artisan make:controller TestController

Step 2: Now, paste the below provided code in the TestController.php file. You can locate this file at app/Http/Controllers.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class TestController extends Controller

{

public function index()

{

echo ‘index’;

}

public function create()

{

echo ‘create’;

}

public function store(Request $request)

{

echo ‘store’;

}

public function show($id)

{

echo ‘show’;

}

public function edit($id)

{

echo ‘edit’;

}

public function update(Request $request, $id)

{

echo ‘update’;

}

public function destroy($id)

{

echo ‘destroy’;

}

}

Step 3: Include the given line of code in the routes.php file. To find this file, follow the path: app/Http.

Route::resource(‘my’,’TestController’);

Step 4: For your convenience, we have tabulated the actions handled by resource controller. Now, after the above 3 steps, you are required to register the methods of TestController. This can be done by registering the controller itself. So, you have to register TestController with the resource.

Verb

URI/Path

Action

Route Name

GET

/test

index

test.index

GET

/test/create

create

test.create

GET

/test/{test}

show

test.show

GET

/test/{test}/edit

edit

test.edit

POST

/test

store

test.store

PUT/PATCH

/test/{test}

update

test.update

DELETE

/test/{test}

destroy

test.destroy

Step 5: Open the PHP’s web server by the mentioned command then follow the given cases.

Description: The URL will execute the edit method of the TestController.

[post_middile_section_ad]

Implicit Controllers

Implicit Controllers are those type of controllers which permits you to define a single route file that is capable of handling all the actions of a controller. This controller can be defined by executing the below command either on the command prompt (cmd) or on the terminal. You will be defining the controller in the route.php.

Route::controller(‘base URI’,’<class-name-of-the-controller>’);

You can replace the <class-name-of-the-controller> field with your desired name for the controller.

Before moving further, keep in mind that you need to start the method name of the controller with the HTTP verb (for example, get or post). Also, the method which starts with the HTTP verb GET, it will handle only GET requests. And the method starting with POST will be focusing on handling the POST requests only. After the appropriate use of the HTTP verb, the name of the method should take care of the title case version of the path or the URI.

To understand implicit controllers, take a look at the following example.

Step 1: Create a new controller under the name ImplicitController. For this, run the following command on the terminal.

laravel> php artisan make:controller ImplicitController –plain

Step 2: Once you are done with the successful creation of the controller, include the given code in the ImplicitController.php. This file can be located in the path app/Http/Controllers.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class ImplicitController extends Controller

{

/**

* Responds to requests to GET /test

*/

public function getIndex()

{

echo ‘index method’;

}

/**

* Responds to requests to GET /test/show/1

*/

public function getShow($id)

{

echo ‘show method’;

}

/**

* Responds to requests to GET /test/admin-profile

*/

public function getAdminProfile()

{

echo ‘admin profile method’;

}

/**

* Responds to requests to POST /test/profile

*/

public function postProfile()

{

echo ‘profile method’;

}

}

Step 3: Now, copy the below-mentioned line of code in the file routes.php. You will be able to find this file on the given path: app/Http.

Route::controller(‘test’,’ImplicitController’);

Controller Injection

For the resolution of all the controllers, Laravel has come up with the solution of Laravel service controller. To use this, you need to type-hint the dependencies. These dependencies will help your controller if it requires its constructor. The injection of the dependencies in the controller instance will be done automatically after its resolution.

Under the controller injection with the following example.

Step 1: Copy the following code of lines in the routes.php file. The file is available at app/Http.

class MyClass{

public $foo = ‘bar’;

}

Route::get(‘/myclass’,’ImplicitController@index’);

Step 2: The second step requires you to include the given code to the ImplicitController.php. You can locate the file under the path app/Http/Controllers.