Sunday, 16 August 2015

HTTP Middleware:-
  • Laravel includes a middleware that verifies the user of an application whether the user is authenticated or not.
  • If the user is not authenticated, then the middleware will redirect the user to the login screen.
  • If it doesn't happen, i.e, if the user is authenticated, the middleware will allow the request to proceed further into the application.
  • There are several middleware included in the Laravel framework, which includes middleware for maintenance, authentication, CSRF protection, and more.
  • All of these middleware are located in the app/Http/Middleware directory.
  • To create a new middleware, use the make:middleware Artisan command:-
                       php artisan make:middleware Middleware1
  • The above command will place a new Middleware1 class within our app/Http/Middleware directory.
  • Discussing it with a suitable example:-
                      <?php

                   namespace App\Http\Middleware;
                   use Closure;
                   class Middleware1
                     {

                       public function request($request, Closure $next)
                            {
                               if ($request‐>input('roll') <= 50) {
                               return redirect('home');
                             }
                                 return $next($request);
                            }
                       }

  • In the above example, we will only allow access to the route if the supplied roll is greater than 50.
  • Otherwise, we will redirect the users back to the "home" URL.
  • If we want a middleware to be run during every HTTP request to our application, we need to list the middleware class in the $middleware property of our app/Http/Kernel.php class.
  • If we would like to assign middleware to specific routes, we should first assign the middleware a shorthand key in our app/Http/Kernel.php file.
  • By default, the $routeMiddleware property contains entries for the middleware included with Laravel.
  • Once the middleware has been defined in the HTTP kernel, we may use the middleware key in the route options array:-
                         Route::get('admin/profile', ['middleware' => 'auth', function () {
                             //
                          }]);
Routing:-
  • Most of the routes for our application in the app/Http/routes.php file, which is loaded by the App\Providers\RouteServiceProvider class.
  • The most basic Laravel routes simply accept a URL and a Closure :
                Route::get('/', function () {
                    return 'Hello World';
                    });

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

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

               Route::delete('foo/bar', function () {
                     return 'Hello World';
                });
  • We need to register a route that responds to multiple HTTP verbs, by using match method.
           Route::match(['get', 'post'], '/', function () {
                   return 'Hello World';
               });
  • It can also be done by using any method.
          Route::any('foo', function () {
                return 'Hello World';
           });
  • Sometimes, we need to capture a user's ID from the URL, by defining route's parameter:-
          Route::get('user/{id}', function ($id) {
               return 'User '.$id;
            });
  • For defining multiple route parameters:-
          Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
               return 'Hello World';
            });
  • The where method is used in routing concept.
  • The where method accepts the name of the parameter and defining a regular expression.
           Route::get('user/{name}', function ($name) {
                //
                })
             ‐>where('name', '[A‐Za‐z]+');

             Route::get('user/{id}', function ($id) {
               //
             })
             ‐>where('id', '[0‐9]+');
  • You may specify a name for a route(named routes) using the as array key when defining the route:-
          Route::get('user/profile', ['as' => 'profile', function () {
             //
          }]);
  • We can also specify route names for controller actions:-
          Route::get('user/profile', [
            'as' => 'profile', 'uses' => 'UserController@showProfile'
          ]);
  • If we are using route groups, we may specify an as keyword in the route group attribute array:-
          Route::group(['as' => 'admin::'], function () {
                             Route::get('dashboard', ['as' => 'dashboard', function () {
                                            // Route named "admin::dashboard"
                            }]);
            });
  • To assign middleware to all routes within a group, we may use the middleware key in the group attribute array.
           Route::group(['middleware' => 'auth'], function () {
                           Route::get('/', function () {
                                 // Uses Auth Middleware
                           });

           Route::get('user/profile', function () {
                    // Uses Auth Middleware
                   });
            });
  • Another common use-case for route groups is assigning the same PHP namespace to a group of controllers.
  • We can use the namespace parameter in our group attribute array to specify the namespace for all controllers within the group:-
          Route::group(['namespace' => 'Admin'], function()
                {
                    // Controllers Within The "App\Http\Controllers\Admin" Namespace
                    Route::group(['namespace' => 'User'], function()
                      {
                          // Controllers Within The "App\Http\Controllers\Admin\User" Namespace
                       });
                 });
  • By default, the RouteServiceProvider includes our routes.php file within a namespace group, allowing us to register controller routes without specifying the full App\Http\Controllers namespace prefix.
  • We only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace root.

Saturday, 15 August 2015

Seeding:-
  • Laravel includes a simple method of seeding our database with test data using seed classes.
  • All seed classes are stored in database/seeds directory.
  • There is no as such naming convention for seeds.
  • By default, a DatabaseSeeder class is defined for us.
  • In this class, by default, "run" method is defined, which can be used to run other seed classes.
  • To generate a seeder, we need to use make:seeder Artisan command.
  • All seeders that are generated will be placed in database/seeders directory.
  • The default method "run()" is called, whenever db:seed Artisan command is executed in the command prompt.
  • To seed our database after we have written seeder classes, we need to execute db:seed Artisan command.
  • By default, db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes.
  • To tun specific seeder class individually, "--class" option is used.
                    php artisan db:seed --class=UserTableSeeder
  • Whatever, changes we have done in seed classes, can be updated or rather re-build by using:-
                    php artisan migrate:refresh --seed

Friday, 14 August 2015

Migrations :-
  • Now, discuss about some concepts in LARAVEL.
  • Migrations are like version control for our  database, allowing a team to easily modify and share the application's database schema.
  • Migrations are typically paired with Laravel's schema builder to easily build our application's database schema.
  • To create a migration, use the make:migration Artisan command:-
          Syntax:-
         php artisan make:migration table_name

          Example:-
          php artisan make:migration create_users_table
  •  Once we run the above command in the DOS prompt, the new migration will be saved in the database/migration directory.
  • Each migration file name contains a timestamp which allows Laravel to understand the order of the migrations.
  • A migration class contains two methods: up and down .
          up :- It is used to add new tables.
          down :- This method is used to reverse the operations performed by the up method.
  • To run the migrations, we need to use the migrate Artisan command, i.e, 
        php artisan migrate
  • If we receive a "class not found" error while running migrations, then we need to run the composer dump‐autoload command
  •  To rollback the latest migration "operation", we need to use the rollback command.
        php artisan migrate:rollback
  •  To rollback all of our application's migrations, we need to use the below command:-
                  php artisan migrate:reset

Saturday, 8 August 2015

Now, its high time, we should now install LARAVEL in our system.

Following are the steps to install it :-
  • First and foremost, download composer.exehttps://getcomposer.org/Composer-Setup.exe
  • While installing composer.exe, select "Install Shell Menu" option and select the path for php.exe file - "C:\wamp\bin\php\php5.5.12". [Note:- I am using Wamp Server]
  • Download Laravel 5 from github - https://github.com/laravel/laravel
  • Open cmd(Command Prompt) and go to folder(by using "cd" command) where "laravel-master" folder is downloaded from the github.
  • Now, just type "composer update" command in the command prompt
  • Now, to run it in the web-browser, just type "php artisan serve". It will start with a port number of 8000, by default. If you want to change the port number, then use this command - "php artisan serve --port=1819". [Note:- Whatever port number, you will type the application will start with that port number] 
  • Last, but not least, just go to the web-browser and type :- "localhost:1819".
Components of Laravel :-



  • When interacting with a Laravel application, a browser sends a request, which is received by a web server and passed on to the Laravel routing engine.
  • The Laravel router receives the request and redirects to the appropriate controller class method based on the routing URL(Uniform Resource Locator) pattern.
  • The controller class then takes over. Commonly, the controller interacts with a model, which is a PHP object that represents an element of the application and is in charge of communicating with the database.
  • After invoking the model, the controller then renders the final view (HTML, CSS, and images) and returns the complete web page to the user’s browser.
  • Laravel promotes the concept that models, views, and controllers should be kept quite separate by storing the code for each of these elements as separate files in separate directories. This is where the Laravel directory structure comes into play.
  • Design patterns such as MVC are created to make a developer’s life easier.
  • Model-View-Controller(MVC) Architecture Pattern :-

    It can be understood properly, with a suitable diagram :-



  • Laravel application structure has an application directory called app/ with three sub-directories: models/, views/, and controllers/.
  • This indicates that Laravel follows the model-view-controller (MVC) architectural pattern, which enforces a separation between “business logic” from the input and presentation logic associated with a graphical user interface (GUI).
  • The MVC design pattern is very popular in the web development space.
  • There are three components :-

    1. The model - It means that the domain that the software is built around. Models are based on real world items such as a person,bank account and etc. For example, if we were building a blog, our models might be post and comment. Models are typically permanent and will be stored often in the database. The model acts as both a gatekeeper and a data store.
    2. The view - It can be stated as the visual representation of a model, It is responsible for generating a user interface, normally based on data in the model. For example, an online store will have a list of products to be displayed on a catalog screen. This list will be accessible via the model, but it will be a view that accesses the list from the model and formats it for the end use. Although the view may present the user with various ways of inputting data, the view itself never handles incoming data. The view’s work is done once the data is displayed.
    3. The controller - It can be termed as the coordinator that provides the link between the view and the model. The controller is responsible for processing input, acting upon the model, and deciding on what action should be performed, such as rendering a view etc.