Laravel - Controllers

Laravel - Controllers

Within MVC, the letter "C" stands for controller. It acts like traffic between views and models. In this chapter, you will learn about controllers in Laravel.

Creating a Controller

Open a command prompt or terminal, depending on your operating system, and enter the following command to create a controller using the Artisan CLI (Command Line Interface).

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

Replace <controller-name> with the name of your controller. This will create a simple constructor when passed an argument - a normal . If you don't want to create a simple constructor, you can just ignore the argument. The generated constructor can be seen in app/Http/Controllers .

You will see that the basic coding has already been done for you and you can add your own code. The created controller can be called from route.php with the following syntax.

Syntax

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

example

Step 1 − Run the following command to create a UserController .

php artisan make:controller UserController --plain

Step 2 − Upon successful execution, you will get the following output.

Step 3 − You can see the created controller in app/Http/Controller/UserController.php with some basic encoding already written for you and you can add your own encoding depending on your needs.

<? php

namespace App \Http\Controllers ; 

use Illuminate \Http\Request ; use App \Http\Requests ; use App \Http\Controllers\Controller ; 
 
 

class UserController extends Controller { // }    
   

Controller Middleware

We have already seen the middleware and it can be used with a controller as well. Middleware can also be assigned to a controller route or in your controller's constructor. You can use the middleware method to assign middleware to a controller. Registered middleware can also be restricted to a specific controller method.

Assigning middleware to a route

Route::get('profile', [
   'middleware' => 'auth',
   'uses' => 'UserController@showProfile'
]);

Here we assign the authorization middleware to the UserController in the route profile.

Assigning middleware in controller constructor

<?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('auth');
   }
}

Here we assign the authentication middleware using the middleware method in the UserController constructor .

example

Step 1 − Add the following lines of code to app/Http/rout.php file and save it.

routes.php

<?php
Route::get('/usercontroller/path',[
   'middleware' => 'First',
   'uses' => 'UserController@showPath'
]);

Step 2 − Create a middleware called FirstMiddleware by executing the following line of code.

php artisan make:middleware FirstMiddleware

Step 3 − Add the following code to the handle method of the newly created FirstMiddleware in app/Http/Middleware .

FirstMiddleware.php

<?php

namespace App\Http\Middleware;
use Closure;

classFirstMiddleware {
   public function handle($request, Closure $next) {
      echo '<br>First Middleware';
      return $next($request);
   }
}

Step 4 − Create a middleware called SecondMiddleware by running the following command.

php artisan make:middleware SecondMiddleware

Step 5 − Add the following code to the handle method of the newly created SecondMiddleware in

app/Http/Middleware .

SecondMiddleware.php

<?php

namespace App\Http\Middleware;
use Closure;

class SecondMiddleware {
   public function handle($request, Closure $next) {
      echo '<br>Second Middleware';
      return $next($request);
   }
}

Step 6 − Create a controller named UserController by executing the following line.

php artisan make:controller UserController --plain
Step 7: Once the URL is successfully executed, you will get the following output:

Step 8 − Copy the following code to app/Http/UserController.php file .

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 9 − Now start the internal php web server by running the following command if you haven't already.

php artisan serve

Step 10 - Visit the following URL.

http://localhost:8000/usercontroller/path

Step 11 − The output will look as shown in the following image.

Restful Resource Controllers

Often when creating an application, we need to perform CRUD (Create, Read, Update, Delete) operations . Laravel makes this job easy for us. Just create a controller and Laravel will automatically provide all methods for CRUD operations. You can also register a single route for all methods in the route.php file.

example

Step 1 − Create a MyController controller by running the following command.

php artisan make:controller MyController

Step 2 - Add the following code to

The file is app/Http/Controllers/MyController.php .

app/Http/Controllers/MyController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyController 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 − Add the following line of code to app/Http/rout.php file .

app/http/routes.php

Route::resource('my','MyController');

Step 4 − We now register all the methods of MyController by registering the controller with the resource. Below is a table of actions performed by the resource controller.

verb Track action Route name
RECEIVE / my index my.index
RECEIVE /my/create Create my.create
MESSAGE / my keep my.store
RECEIVE /my mine} show my.show
RECEIVE /my/{my}/edit edit my.edit
PUT/PATCH /my mine} Refresh my.update
DELETE /my mine} destroy my.destroy

Step 5 − Try the URLs shown in the following table.

URL Description output image
http://localhost:8000/mine Executes the index method of MyController.php index
http://localhost:8000/my/create Executes the create method of MyController.php Create
http://localhost:8000/me/1 Executes the show method of MyController.php show
http://localhost:8000/mine/1/edit Executes the edit method of MyController.php edit

Implicit Controllers

Implicit controllers allow you to define one route to handle each action in a controller. You can define it in the route.php file using the Route: controller method as shown below.

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

Replace <class-name-of-the-controller> with the class name you gave your controller.

The controller method name must start with an HTTP verb, like get or post. If you start with get it will only process the get request and if it starts with post it will process the post request. Once you can use the HTTP verb, you can give any name to the method, but it must match the version of the URI in the header case.

example

Step 1 − Run the below command to create a controller. We have kept the class name ImplicitController . You can give any name of your choice.

php artisan make:controller ImplicitController --plain

Step 2 − After successful completion of step 1, you will get the following output −

Step 3 - Copy the following code into

The file is app/Http/Controllers/ImplicitController.php .

app/Http/Controllers/ImplicitController.php

<?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 4 − Add the following line to the app/Http/rout.php file to route requests to the specified controller.

app/http/routes.php

Route::controller('test','ImplicitController');

Constructor Injection

The Laravel service container is used to resolve all Laravel controllers. As a result, you can print any dependencies your controller might need in its constructor. The dependencies will be automatically resolved and injected into the controller instance.

example

Step 1 − Add the following code to app/Http/rout.php file .

app/http/routes.php

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Step 2 - Add the following code to

The file is app/Http/Controllers/ImplicitController.php .

app/Http/Controllers/ImplicitController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImplicitController extends Controller {
   private $myclass;
   
   public function __construct(\MyClass $myclass) {
      $this->myclass = $myclass;
   }
   public function index() {
      dd($this->myclass);
   }
}

Step 3 − Visit the following URL to test the constructor injection.

http://localhost:8000/myclass

Step 4 − The output will look as shown in the following image.

Method Injection

In addition to constructor injection, you can also inject hints depending on your controller's action methods.

example

Step 1 − Add the following code to app/Http/rout.php file .

app/http/routes.php

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Step 2 - Add the following code to

The file is app/Http/Controllers/ImplicitController.php .

app/Http/Controllers/ImplicitController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImplicitController extends Controller {
   public function index(\MyClass $myclass) {
      dd($myclass);
}
} 

Step 3 − Visit the following URL to test the constructor injection.

http://localhost:8000/myclass

This will give the following result −