Tuesday 8 August 2017

Laravel - Controllers


Basic Controllers

In MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views and Models.

Creating a Controller

Open the command prompt or terminal based on the operating system you are using and type the following command to create controller using the Artisan CLI (Command Line Interface).
php artisan make:controller <controller-name> --plain
Replace the <controller-name> with the name of your controller. This will create a plain constructor as we are passing the argument — plain. If you don’t want to create a plain constructor, you can simply ignore the argument. The created constructor can be seen at app/Http/Controllers. You will see that some basic coding has already been done for you and you can add your custom coding. The created controller can be called from routes.php by the following syntax.

Syntax

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

Example

Step 1 − Execute the following command to create UserController.
php artisan make:controller UserController --plain
Step 2 − After successful execution, you will receive the following output.
Step 3 − You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need.
<?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 seen middleware before and it can be used with controller also. Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller.

Assigning Middleware to Route

Route::get('profile', [
   'middleware' => 'auth',
   'uses' => 'UserController@showProfile'
]);
Here we are assigning auth middleware to UserController in profile route.

Assigning Middleware within Controller’s 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 are assigning auth middleware using the middleware method in the UserController’s constructor.

Example

Step 1 − Add the following lines to the app/Http/routes.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.
php artisan make:middleware FirstMiddleware
Step 3 − Add the following code in the handle method of the newly created FirstMiddleware at app/Http/Middleware.
FirstMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;

class FirstMiddleware {
   public function handle($request, Closure $next) {
      echo '<br>First Middleware';
      return $next($request);
   }
}
Step 4 − Create a middleware called SecondMiddleware by executing the following line.
php artisan make:middleware SecondMiddleware
Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at 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 called UserController by executing the following line.
php artisan make:controller UserController --plain
Step 7 − After successful execution of the URL, you will receive 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 launch the php’s internal web server by executing the following command, if you haven’t executed it yet.
php artisan serve
Step 10 − Visit the following URL.
http://localhost:8000/usercontroller/path
Step 11 − The output will appear as shown in the following image.

Restful Resource Controllers

Often while making 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 the methods for the CRUD operations. You can also register a single route for all the methods in routes.php file.

Example

Step 1 − Create a controller called MyController by executing the following command.
php artisan make:controller MyController
Step 2 − Add the following code in app/Http/Controllers/MyController.php file.
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 in app/Http/routes.php file.
app/Http/routes.php
Route::resource('my','MyController');
Step 4 − We are now registering all the methods of MyController by registering a controller with resource. Below is the table of actions handled by resource controller.
Verb Path Action Route Name
GET /my index my.index
GET /my/create create my.create
POST /my store my.store
GET /my/{my} show my.show
GET /my/{my}/edit edit my.edit
PUT/PATCH /my/{my} update my.update
DELETE /my/{my} destroy my.destroy
Step 5 − Try executing the URLs shown in the following table.
URL Description Output Image
http://localhost:8000/my Executes index method of MyController.php index
http://localhost:8000/my/create Executes create method of MyController.php create
http://localhost:8000/my/1 Executes show method of MyController.php show
http://localhost:8000/my/1/edit Executes edit method of MyController.php edit

Implicit Controllers

Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route:controller method as shown below.
Route::controller(‘base URI’,’<class-name-of-the-controller>’);
Replace the <class-name-of-the-controller> with the class name that you have given to your controller.
The method name of the controller should start with HTTP verb like get or post. If you start it with get, it will handle only get request and if it starts with post then it will handle the post request. After the HTTP verb you can, you can give any name to the method but it should follow the title case version of the URI.

Example

Step 1 − Execute the below command to create a controller. We have kept the class name ImplicitController. You can give any name of your choice to the class.
php artisan make:controller ImplicitController --plain
Step 2 − After successful execution, you will receive the following output −
Step 3 − Copy the following code to app/Http/Controllers/ImplicitController.php file.
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 app/Http/routes.php file to route the requests to 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 are able to type-hint any dependencies your controller may need in its constructor. The dependencies will automatically be resolved and injected into the controller instance.

Example

Step 1 − Add the following code to app/Http/routes.php file.
app/Http/routes.php
class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');
Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file.
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 appear as shown in the following image.

Method Injection

In addition to constructor injection, you may also type — hint dependencies on your controller's action methods.

Example

Step 1 − Add the following code to app/Http/routes.php file.
app/Http/routes.php
class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');
Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file.
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
It will produce the following output −

Monday 7 August 2017

Laravel - Middleware


Define Middleware

As the name suggest, Middleware acts as a middle man between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.
Middleware can be created by executing the following command −
php artisan make:middleware <middleware-name>
Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Example

Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −
php artisan make:middleware AgeMiddleware
Step 2 − After successful execution of the command, you will receive the following output −
Step 3AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.
<?php
namespace App\Http\Middleware;
use Closure;

class AgeMiddleware {
   public function handle($request, Closure $next) {
      return $next($request);
   }
}

Register Middleware

We need to register each and every middleware before using it. There are two types of Middleware in Laravel.
The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.
To register the global middleware, list the class at the end of $middleware property.
protected $middleware = [
   \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
   \App\Http\Middleware\EncryptCookies::class,
   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
   \Illuminate\Session\Middleware\StartSession::class,
   \Illuminate\View\Middleware\ShareErrorsFromSession::class,
   \App\Http\Middleware\VerifyCsrfToken::class,
];
To register the route specific middleware, add the key and value to $routeMiddleware property.
protected $routeMiddleware = [
   'auth' => \App\Http\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];

Example

We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.
The following is the code for app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
   protected $middleware = [
      \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
      \App\Http\Middleware\EncryptCookies::class,
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
      \Illuminate\Session\Middleware\StartSession::class,
      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      \App\Http\Middleware\VerifyCsrfToken::class,
   ];
  
   protected $routeMiddleware = [
      'auth' => \App\Http\Middleware\Authenticate::class,
      'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
      'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
      'Age' => \App\Http\Middleware\AgeMiddleware::class,
   ];
}

Middleware Parameters

We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.
public function handle($request, Closure $next) {
   return $next($request);
}

Example

Step 1 − Create RoleMiddleware by executing the following command −
php artisan make:middleware RoleMiddleware
Step 2 − After successful execution, you will receive the following output
Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.
<?php
namespace App\Http\Middleware;
use Closure;

class RoleMiddleware {
   public function handle($request, Closure $next, $role) {
      echo "Role: ".$role;
      return $next($request);
   }
}
Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.
Step 5 − Execute the following command to create TestController
php artisan make:controller TestController --plain
Step 6 − After successful execution, you will receive the following output −
Step 7 − Copy the following code to app/Http/TestController.php file.
app/Http/TestController.php
<?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 "<br>Test Controller.";
   }
}
Step 8 − Add the following line of code in app/Http/routes.php file.
app/Http/routes.php
Route::get('role',[
   'middleware' => 'Role:editor',
   'uses' => 'TestController@index',
]);
Step 9 − Visit the following URL to test the Middleware with parameters
http://localhost:8000/role
Step 10 − The output will appear as shown in the following image.

Terminable Middleware

Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with “terminate” method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.

Example

Step 1 − Create TerminateMiddleware by executing the below command.
php artisan make:middleware TerminateMiddleware
Step 2 − This will produce the following output −
Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.
<?php
namespace App\Http\Middleware;
use Closure;

class TerminateMiddleware {
   public function handle($request, Closure $next) {
      echo "Executing statements of handle method of TerminateMiddleware.";
      return $next($request);
   }
   
   public function terminate($request, $response){
      echo "<br>Executing statements of terminate method of TerminateMiddleware.";
   }
}
Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware.
Step 5 − Execute the following command to create ABCController.
php artisan make:controller ABCController --plain
Step 6 − After successful execution of the URL, you will receive the following output −
Step 7 − Copy the following code to app/Http/ABCController.php file.
app/Http/ABCController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ABCController extends Controller {
   public function index(){
      echo "<br>ABC Controller.";
   }
}
Step 8 − Add the following line of code in app/Http/routes.php file.
app/Http/routes.php
Route::get('terminate',[
   'middleware' => 'terminate',
   'uses' => 'ABCController@index',
]);
Step 9 − Visit the following URL to test the Terminable Middleware.
http://localhost:8000/terminate
Step 10 − The output will appear as shown in the following image.

Sunday 6 August 2017

Laravel - Routing


Basic Routing

Basic routing is meant to route your request to an appropriate controller. The routes of the application can be defined in app/Http/routes.php file. Here is the general route syntax for each of the possible request.
Route::get('/', function () {
   return 'Hello World';
});

Route::post('foo/bar', function () {
   return 'Hello World';
});

Route::put('foo/bar', function () {
   //
});

Route::delete('foo/bar', function () {
   //
});
Let us now understand how to see the Laravel homepage with the help of routing.

Example

app/Http/routes.php
<?php
Route::get('/', function () {
   return view('welcome');
});
resources/view/welcome.blade.php
<!DOCTYPE html>
<html>
   
   <head>
      <title>Laravel</title>
      <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" 
         type = "text/css">
      
      <style>
         html, body {
            height: 100%;
         }
         body {
            margin: 0;
            padding: 0;
            width: 100%;
            display: table;
            font-weight: 100;
            font-family: 'Lato';
         }
         .container {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
         }
         .content {
            text-align: center;
            display: inline-block;
         }
         .title {
            font-size: 96px;
         }
      </style>
   </head>
   
   <body>
      <div class = "container">
         
         <div class = "content">
            <div class = "title">Laravel 5</div>
         </div>
   
      </div>
   </body>

</html>
The routing mechanism is depicted in the following image −
Let us now understand the steps in detail −
  • Step 1 − First, we need to execute the root URL of the application.
  • Step 2 − The executed URL will match with the appropriate method in the route.php file. In our case, it will match to get the method and the root (‘/’) URL. This will execute the related function.
  • Step 3 − The function calls the template file resources/views/welcome.blade.php. The function later calls the view() function with argument ‘welcome’ without using the blade.php. It will produce the following HTML output.

Routing Parameters

Often in the application, we intend to capture the parameters passed with the URL. To do this, we need to modify the code in routes.php file accordingly. There are two ways by which we can capture the parameters passed with the URL.
  • Required Parameters
  • Optional Parameters

Required Parameters

These parameters must be present in the URL. For example, you may intend to capture the ID from the URL to do something with that ID. Here is the sample coding for routes.php file for that purpose.
Route::get('ID/{id}',function($id){
   echo 'ID: '.$id;
});
Whatever argument that we pass after the root URL (http://localhost:8000/ID/5), it will be stored in $id and we can use that parameter for further processing but here we are simply displaying it. We can pass it onto view or controller for further processing.

Optional Parameters

There are some parameters which may or may not be present in the URL and in such cases we can use the optional parameters. The presence of these parameters is not necessary in the URL. These parameters are indicated by “?” sign after the name of the parameters. Here is the sample coding for routes.php file for that purpose.
Route::get('/user/{name?}',function($name = 'Virat'){
   echo "Name: ".$name;
});

Example

routes.php
<?php

// First Route method – Root URL will match this method
Route::get('/', function () {
   return view('welcome');
});

// Second Route method – Root URL with ID will match this method
Route::get('ID/{id}',function($id){
   echo 'ID: '.$id;
});

// Third Route method – Root URL with or without name will match this method
Route::get('/user/{name?}',function($name = 'Virat Gandhi'){
   echo "Name: ".$name;
});
Step 1 − Here, we have defined 3 routes with get methods for different purposes. If we execute the below URL then it will execute the first method.
http://localhost:8000
Step 2 − After successful execution of the URL, you will receive the following output −
Step 3 − If we execute the below URL, it will execute the 2nd method and the argument/parameter ID will be passed to the variable $id.
http://localhost:8000/ID/5
Step 4 − After successful execution of the URL, you will receive the following output −
Step 5 − If we execute the below URL, it will execute the 3rd method and the optional argument/parameter name will be passed to the variable $name. The last argument ‘Virat’ is optional. If you remove it, the default name will be used that we have passed in the function as ‘Virat Gandhi’
http://localhost:8000/user/Virat
Step 6 − After successful execution of the URL, you will receive the following output −
Note − Regular expression can also be used to match the parameters.

Saturday 5 August 2017

Laravel - Configuration


The config directory, as the name implies, contains all of your application's configuration files. In this directory, you will find various files needed to configure database, session, mail, application, services etc.

Basic Configuration

  • After installing Laravel, the first thing we need to do is to set the write permission for the directory storage and bootstrap/cache.
  • Generate Application key to secure session and other encrypted data. If the root directory doesn’t contain the .env file then rename the .env.example to .env file and execute the following command where you have installed Laravel. The newly generated key can be seen in the .env file.
  • You can also configure the locale, time zone, etc. of the application in the config/app.php file.

Environmental Configuration

Laravel provides facility to run your application in different environment like testing, production etc. You can configure the environment of your application in the .env file of the root directory of your application. If you have installed Laravel using composer, this file will automatically be created.
In case you haven’t installed Laravel, you can simply rename the .env.example file to .env file. A sample of Laravel.env file is shown below.
Notice the text underlined gray in the above image. Local environment variable has been set. It can further be changed to production or testing as per your requirement.

Database Configuration

The database of your application can be configured from config/database.php file. You can set configuration parameters that can be used by different databases and you can also set the default one to use.

Naming the Application

The App Directory, by default, is namespaced under App. To rename it, you can execute the following command and rename the namespace.
php artisan app:name <name-of-your-application>
Replace the <name-of-your-application> with the new name of your application that you want to give.

Maintenance Mode

We need to modify our website on a regular basis. The website needs to be put on maintenance mode for this. Laravel has made this job easier. There are two artisan commands which are used to start and stop the maintenance mode which are described below.

Start Maintenance Mode

To start the maintenance mode, simply execute the following command.
php artisan down
After successful execution, you will receive the following output −
It will activate the Maintenance mode and all the request to server will be redirected to a single maintenance page as shown in the following screenshot.

Stop Maintenance Mode

  • After making changes to your website and to start it again, execute the following command.
php artisan up
  • After successful execution, you will receive the following output −

Friday 4 August 2017

Laravel - Application Structure


Root Directory

The root directory of Laravel contains various folders and files as shown in the following figure.
  • app − This directory contains the core code of the application.
  • bootstrap − This directory contains the application bootstrapping script.
  • config − This directory contains configuration files of application.
  • database − This folder contains your database migration and seeds.
  • public − This is the application’s document root. It starts the Laravel application. It also contains the assets of the application like JavaScript, CSS, Images, etc.
  • resources − This directory contains raw assets such as the LESS & Sass files, localization and language files, and Templates that are rendered as HTML.
  • storage − This directory contains App storage, like file uploads etc. Framework storage (cache), and application-generated logs.
  • test − This directory contains various test cases.
  • vendor − This directory contains composer dependencies.

App Directory

This is the application directory. It contains a variety of additional directories, which are described below −
  • Console − All the artisan commands are stored in this directory.
  • Events − This directory stores events that your application can raise. Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling.
  • Exceptions − This directory contains your application's exception handler and is also a good place to stick any exceptions thrown by your application.
  • Http − This directory contains your controllers, filters, and requests.
  • Jobs − This directory contains the queueable jobs for your application.
  • Listeners − This directory contains the handler classes for your events. Handlers receive an event and perform logic in response to the event being fired. For example, a UserRegistered event might be handled by a SendWelcomeEmail listener.
  • Policies − This directory contains various policies of the application
  • Providers − This directory contains various service providers.