Friday, October 26, 2018

How to call Artisan Command from Controller or Route or Command line

1.Call Artisan Command from Command Line
You can call your artisan command from command line like :
php artisan cache:clear
  1.  Call Artisan Command from Controller
    1. routes.php
      Add this get method in your routing file.
      Route::get(‘test’, ‘TestController@test’);
      Now Create a controller file name as “TestController.php” under “app\Http\Controllers”.
      <?php
      namespace App\Http\Controllers;
      use App\Http\Controllers\Controller;
      use Artisan;
      class TestController extends Controller {
           
          public function test(){
              Artisan::call('cache:clear');      
          }  
           
      }
      ?>
      Now when you call the test method like /test in your browser then the Artisan command will fire.


      You can call your artisan command from route file as well.
      routes.php
      Route::get(‘/my_artisan’, function () {Artisan::call(“cache:clear”););});
      Now you can execute the above route from your browser like /my_artisan
      Now we will discuss all Artisan command one by one. First of all, to see what commands are available in laravel we will execute below command:
      Route::get('/my_artisan', function () {Artisan::call("list");dd(Artisan::output());});
      Which will output all available CLI commands
      Usage:\n
        command [options] [arguments]\n
      \n
      Options:\n
        -h, --help            Display this help message\n
        -q, --quiet           Do not output any message\n
        -V, --version         Display this application version\n
            --ansi            Force ANSI output\n
            --no-ansi         Disable ANSI output\n
        -n, --no-interaction  Do not ask any interactive question\n
            --env[=ENV]       The environment the command should run under.\n
        -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug\n
      \n
      Available commands:\n
        clear-compiled      Remove the compiled class file\n
        down                Put the application into maintenance mode\n
        env                 Display the current framework environment\n
        help                Displays help for a command\n
        inspire             Display an inspiring quote\n
        list                Lists commands\n
        migrate             Run the database migrations\n
        optimize            Optimize the framework for better performance\n
        serve               Serve the application on the PHP development server\n
        tinker              Interact with your application\n
        up                  Bring the application out of maintenance mode\n
       app\n
        app:name            Set the application namespace\n
       auth\n
        auth:clear-resets   Flush expired password reset tokens\n
       cache\n
        cache:clear         Flush the application cache\n
        cache:table         Create a migration for the cache database table\n
       config\n
        config:cache        Create a cache file for faster configuration loading\n
        config:clear        Remove the configuration cache file\n
       db\n
        db:seed             Seed the database with records\n
       event\n
        event:generate      Generate the missing events and listeners based on registration\n
       handler\n
        handler:command     Create a new command handler class\n
        handler:event       Create a new event handler class\n
       key\n
        key:generate        Set the application key\n
       make\n
        make:command        Create a new command class\n
        make:console        Create a new Artisan command\n
        make:controller     Create a new resource controller class\n
        make:event          Create a new event class\n
        make:job            Create a new job class\n
        make:listener       Create a new event listener class\n
        make:middleware     Create a new middleware class\n
        make:migration      Create a new migration file\n
        make:model          Create a new Eloquent model class\n
        make:provider       Create a new service provider class\n
        make:request        Create a new form request class\n
        make:seeder         Create a new seeder class\n
       migrate\n
        migrate:install     Create the migration repository\n
        migrate:refresh     Reset and re-run all migrations\n
        migrate:reset       Rollback all database migrations\n
        migrate:rollback    Rollback the last database migration\n
        migrate:status      Show the status of each migration\n
       queue\n
        queue:failed        List all of the failed queue jobs\n
        queue:failed-table  Create a migration for the failed queue jobs database table\n
        queue:flush         Flush all of the failed queue jobs\n
        queue:forget        Delete a failed queue job\n
        queue:listen        Listen to a given queue\n
        queue:restart       Restart queue worker daemons after their current job\n
        queue:retry         Retry a failed queue job\n
        queue:subscribe     Subscribe a URL to an Iron.io push queue\n
        queue:table         Create a migration for the queue jobs database table\n
        queue:work          Process the next job on a queue\n
       route\n
        route:cache         Create a route cache file for faster route registration\n
        route:clear         Remove the route cache file\n
        route:list          List all registered routes\n
       schedule\n
        schedule:run        Run the scheduled commands\n
       session\n
        session:table       Create a migration for the session database table\n
       vendor\n
        vendor:publish      Publish any publishable assets from vendor packages\n
       view\n
        view:clear          Clear all compiled view files\n
      clear-compiled
      Route::get('/my_artisan', function () {Artisan::call('clear-compiled');}); 
      This command remove the compiled class file from “/bootstrap/cache” folder.
      clear-compiled
      Route::get('/my_artisan', function () {Artisan::call('down');});
      This command put your application into maintenance mode and it creates a file name as “down” under “/storage/framework” folder.
      env
      Route::get('/my_artisan', function () {Artisan::call('env');});
      It displays your current application environment like “local” . This function read the “APP_ENV” variable’s value from .env file which is located in here “/.env”
      help
      Route::get('/my_artisan', function () {Artisan::call('help');dd(Artisan::output())});
      If you want to take help for a command then you can use it. Which returns below result:
      Usage:\n
        help [options] [--] [<command_name>]\n
      \n
      Arguments:\n
        command               The command to execute\n
        command_name          The command name [default: "help"]\n
      \n
      Options:\n
            --xml             To output help as XML\n
            --format=FORMAT   The output format (txt, xml, json, or md) [default: "txt"]\n
            --raw             To output raw command help\n
        -h, --help            Display this help message\n
        -q, --quiet           Do not output any message\n
        -V, --version         Display this application version\n
            --ansi            Force ANSI output\n
            --no-ansi         Disable ANSI output\n
        -n, --no-interaction  Do not ask any interactive question\n
            --env[=ENV]       The environment the command should run under.\n
        -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug\n
      \n
      Help:\n
       The help command displays help for a given command:\n
       \n
         php /cs/public/index.php help list\n
       \n
       You can also output the help in other formats by using the --format option:\n
       \n
         php /cs/public/index.php help --format=xml list\n
       \n
       To display the list of available commands, please use the list command.\n
      inspire
      Route::get('/my_artisan', function () {Artisan::call('inspire');dd(Artisan::output())});
      This function display an inspiring quotes.
      list
      Route::get('/my_artisan', function () {Artisan::call('list');dd(Artisan::output())});
      Display all available commands.Earlier I have already discussed about this command.
      optimize
      Route::get('/my_artisan', function () {Artisan::call('optimize',['--force'=>'force']);});
      This function creates 2 files (compiled.php and services.json) under \bootstrap\cache folder which is used for better performance.
      serve
      Route::get('/my_artisan', function () {Artisan::call("serve",["--host"=>'127.0.0.1']);});
      This function will serve the application on the PHP development server.
      up
      You can’t use this function from controller or route. You must execute from command line to make it live.
      php artisan up 
      This command makes your application live from maintenance mode.
      app:name
      Route::get('/my_artisan', function () { (Artisan::call("app:name",['name'=>'TestApp']));});
      This function set your application namespace.
      auth:clear-resets
      Route::get('/my_artisan', function () { (Artisan::call("auth:clear-resets"));});
      This command deletes expired password tokens which is less than one hour from current time, from password_resets table.
      cache:clear
      Route::get('/my_artisan', function () {Artisan::call("cache:clear");});
      Deletes application cache from “\storage\framework\cache” folder.
      cache:clear
      Route::get('/my_artisan', function () { (Artisan::call("cache:table"));});
      This command creates a migration for the cache table under this path “\database\migrations\2016_06_10_112327_create_cache_table.php”
      The filename is create according to current date and time like this format: YYYY_mm_dd_His_create_cache_table.php
      config:cache
      Route::get('/my_artisan', function () { (Artisan::call("config:cache"));});
      This function creates a cache file for faster configuration loading and it creates a “cache.php” file under “\bootstrap\cache\” folder.
      config:clear
      Route::get('/my_artisan', function () { (Artisan::call("config:clear"));});
      Remove configuration file which created by “config:cache” command
      event:generate
      Route::get('/my_artisan', function () {Artisan::call("event:generate");});
      This function generates the missing events and listeners based on registration which is defined in “\App\Providers\EventServiceProvider.php” files like below :
      protected $listen = [
          'App\Events\SomeEvent' => [
              'App\Listeners\EventListener',
          ],
      ];
      Above command will genaretes 1 Events file under “\App\Events\SomeEvent.php” and 1 Listners file under “\App\Listeners\EventListener.php”
      handler:command
      Route::get('/my_artisan', function () {Artisan::call("handler:command",['name'=> 'TestCommand']);});
      This function creates a new command handler class under “\app\Handlers\Commands\TestCommand.php”
      handler:event
      Route::get('/my_artisan', function () {Artisan::call("handler:event",['name'=> 'TestEvent']);});
      Create a new command handler class under “\app\Handlers\Events\TestEvent.php”
      key:generate
      Route::get('/my_artisan', function () { (Artisan::call("key:generate"));});
      Generates a randomly application key and set the value in APP_KEY in .env file.
      make:command
      Route::get('/my_artisan', function () { (Artisan::call("make:command",['name'=> 'TestCommand']));});
      Create a new command Class under “\app\Commands\TestCommand.php”
      make:console
      Route::get('/my_artisan', function () { (Artisan::call("make:console",['name'=> 'TestConsole']));});
      Create a new Artisan command under “\app\Console\Commands\TestConsole.php”;
      make:controller
      Route::get('/my_artisan', function () { (Artisan::call("make:controller",['name'=> 'TestController']));});  
      Create a new resource controller Class under “\app\Http\Controllers\TestController.php”
      make:event
      Route::get('/my_artisan', function () { (Artisan::call("make:event",['name'=> 'TestEvent']));});
      Create a new event Class under “\app\Events\TestEvent.php”
      make:job
      Route::get('/my_artisan', function () { (Artisan::call("make:job",['name'=> 'TestJob']));});
      Create a new job Class under “\app\Jobs\TestJob.php”
      make:listener
      Route::get('/my_artisan', function () { (Artisan::call("make:listener",['name'=> 'TestListener']));});
      Create a new event listner Class under “\app\Listeners\TestListener.php”
      make:middleware
      Route::get('/my_artisan', function () { (Artisan::call("make:middleware",['name'=> 'TestMiddleware']));});
      Create a new middleware Class under “\app\Http\Middleware\TestMiddleware.php”
      make:migration
      Route::get('/my_artisan', function () { (Artisan::call("make:migration",['name'=> 'TestMigration']));});
      Create a new migration file under “\database\migrations\2016_06_11_110210_TestMigration.php”
      make:model
      Route::get('/my_artisan', function () { (Artisan::call("make:model",['name'=> 'TestModel']));});
      Create a new Eloquent Model Class under “\app\TestModel.php”
      make:provider
      Route::get('/my_artisan', function () { (Artisan::call("make:provider",['name'=> 'TestProviders']));});
      Create a new service provider Class under “\app\Providers\TestProviders.php”
      make:request
      Route::get('/my_artisan', function () { (Artisan::call("make:request",['name'=> 'TestRequests']));});
      Create a new form request Class under “\app\Http\Requests\TestRequests.php”
      make:seeder
      Route::get('/my_artisan', function () { (Artisan::call("make:seeder",['name'=> 'TestSeeder']));});
      Create a new seeder Class under “\database\seeds\TestSeeder.php” By default it generates a single method name “run()”.

      How to use migrate command?

      migrate
      Route::get('/my_artisan, function () { (Artisan::call("migrate"));});
      Run the database migrations
      migrate:install
      Route::get('/my_artisan, function () { (Artisan::call("migrate:install"));});
      Create the migration repository table name as “migrations” in your database.
      migrate:refresh
      Route::get('/my_artisan', function () { (Artisan::call("migrate:refresh"));});
      Reset and re-run all migration. It means it creates all the table which is under this “\database\migrations”
      migrate:reset
      Route::get('/my_artisan', function () { (Artisan::call("migrate:reset"));});
      Rollback all database migration. It means it deletes all the tables from your database except migration table (But table structure will remain only).
      migrate:rollback
      Route::get('/my_artisan', function () { (Artisan::call("migrate:rollback"));});
      Rollback the last database migration. It means it executes the last command which you have used recently.
      migrate:status
      Route::get('/my_artisan', function () {Artisan::call("migrate:status");dd(Artisan::output());});
      Above function shows the status of each migration like below:
      +------+------------------------------------------------+\n
      | Ran? | Migration                                      |\n
      +------+------------------------------------------------+\n
      | N    | 2014_10_12_000000_create_users_table           |\n
      | N    | 2014_10_12_100000_create_password_resets_table |\n
      | N    | 2016_04_02_131806_create_jobs_table            |\n
      | N    | 2016_06_10_112609_create_cache_table           |\n
      +------+------------------------------------------------+\n
      queue:failed
      Route::get('/my_artisan', function () {Artisan::call('queue:failed');});
      List all of the failed queue jobs from “failed_jobs” Table. Result will look like below :
      +----+------------+---------+---------------------+-----------+\n
      | ID | Connection | Queue   | Class               | Failed At |\n
      +----+------------+---------+---------------------+-----------+\n
      | 1  | Test       | Testing | 2016-06-21 13:19:37 |           |\n
      +----+------------+---------+---------------------+-----------+\n
      queue:failed-table
      Route::get('/my_artisan', function () {Artisan::call('queue:failed-table');});
      Create a migration for the failed queue jobs database table under “\database\migrations\2016_06_14_103032_create_failed_jobs_table.php”
      queue:flush
      Route::get('/my_artisan', function () {Artisan::call('queue:flush');});
      Delete all failed jobs from failed_jobs Table
      queue:forget
      Route::get('/my_artisan', function () { (Artisan::call("queue:forget",['id'=>'2']));});
      Delete a failed queue job from failed_jobs Table
      queue:restart
      Route::get('/my_artisan', function () {Artisan::call('queue:restart');});
      Restart queue worker daemons after their current job
      queue:table
      Route::get('/my_artisan', function () {Artisan::call('queue:table');});
      create a migration for the queue jobs database table under “\database\migrations\2016_06_14_121326_create_jobs_table.php”

      How to use Route Artisan Command

      route:cache
      Route::get('/my_artisan', function () {Artisan::call("route:cache");});
      If you run above command then might be you get following error :
      Unable to prepare route [/] for serialization. Uses Closure.
      It means you can use Closure only in your route file.
      You can call this artisan from from either controller’s method or from command line:
      Controller : Artisan::call("route:cache");
      CLI : php artisan route:cache
      It creates a route cache file for faster route registration under “\bootstrap\cache\routes.php”
      route:clear
      Route::get('/my_artisan', function () { (Artisan::call("route:clear"));});
      Again you need to remove from either controller’s method or from command line. This command remove the route cache file.
      route:clear
      Route::get('/my_artisan', function () {Artisan::call("route:list");dd(Artisan::output());});
      This function display your all registered routes. The output will look like below:
      +--------+----------+------------+------+--------------------------------------------------+------------+\n
      | Domain | Method   | URI        | Name | Action                                           | Middleware |\n
      +--------+----------+------------+------+--------------------------------------------------+------------+\n
      |        | GET|HEAD | /          |      | Closure                                          |            |\n
      |        | GET|HEAD | foo        |      | Closure                                          |            |\n
      |        | GET|HEAD | register   |      | App\Http\Controllers\UserController@register     |            |\n
      |        | POST     | save_user  |      | App\Http\Controllers\UserController@SaveRegister |            |\n
      |        | GET|HEAD | users/{id} |      | Closure                                          |            |\n
      +--------+----------+------------+------+--------------------------------------------------+------------+\n
      route:clear
      Route::get('/my_artisan', function () {Artisan::call("schedule:run");});
      Run the scheduled commands
      session:table
      Route::get('/my_artisan', function () {Artisan::call("session:table");});
      Create a migration for the session database table under “\database\migrations\2016_06_16_131413_create_session_table.php”
      view:clear
      Route::get('/my_artisan', function () {Artisan::call("view:clear");});
      Clear all view compiled files from “\storage\framework\views” folder
      Keep in touch for more tutorials.



       

How to authenticate token in laravel (Part0)

  1. Introduct
           Authentication is one of the most important parts of any web application.For decades, cookies and server-based authentication were the easiest solution. However, handling authentication in modern Mobile and Single Page Applications can be tricky, and demand a better approach. The best known solutions to authentication problems for APIs are the OAuth 2.0 and the JSON Web Token (JWT).


What is a JSON Web Token?

A JSON Web Token, or JWT, is used to send information that can be verified and trusted by means of a digital signature. It comprises a compact and URL-safe JSON object, which is cryptographically signed to verify its authenticity, and which can also be encrypted if the payload contains sensitive information.
Because of it’s compact structure, JWT is usually used in HTTP Authorization headers or URL query parameters.

Structure of a JSON Web Token

A JWT is represented as a sequence of base64url encoded values that are separated by period characters.



    
JSON Web Token example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3R
fY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.
yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw
The header contains the metadata for the token and it minimally contains the type of signature and the encryption algorithm.
 
Example Header
{ “alg”: “HS256”, “typ”: “JWT” }
 
This JWT Header declares that the encoded object is a JSON Web Token, and that it is signed using the HMAC SHA-256 algorithm.
Once this is base64 encoded, we have the first part of our JWT.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload (Claims)

In the context of JWT, a claim can be defined as a statement about an entity (typically, the user), as well as additional meta data about the token itself. The claim contains the information we want to transmit, and that the server can use to properly handle authentication. There are multiple claims we can provide; these include registered claim names, public claim names and private claim names.
Registered Claims
These are the claims that are registered in the IANA JSON Web Token Claims registry. These claims are not intended to be mandatory but rather to provide a starting point for a set of useful, interoperable claims.
These include:
  • iss: The issuer of the token
  • sub: The subject of the token
  • aud: The audience of the token
  • exp: Token expiration time defined in Unix time
  • nbf: “Not before” time that identifies the time before which the JWT must not be accepted for processing
  • iat: “Issued at” time, in Unix time, at which the token was issued
  • jti: JWT ID claim provides a unique identifier for the JWT
Public Claims
Public claims need to have collision-resistant names. By making the name a URI or URN naming collisions are avoided for JWTs where the sender and receiver are not part of a closed network.
An example of a public claim name could be: https://www.toptal.com/jwt_claims/is_admin, and the best practice is to place a file at that location describing the claim so that it can be dereferenced for documentation.
Private Claims
Private claim-names may be used in places where JWTs are only exchanged in a closed environment between known systems, such as inside an enterprise. These are claims that we can define ourselves, like user IDs, user roles, or any other information.
Using claim-names that might have conflicting semantic meanings outside of a closed or private system are subject to collision, so use them with caution.
It is important to note that we want to keep a web token as small as possible, so use only necessary data inside public and private claims.
Example Payload
{
  “iss”: “toptal.com”,
  “exp”: 1426420800,
  “https://www.toptal.com/jwt_claims/is_admin”: true,
  “company”: “Toptal”,
  “awesome”: true
}
This example payload has two registered claims, one public claim and two private claims. Once it is base64 encoded, we have the second part of our JWT.
eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3R
fY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0
 

Signature

The JWT standard follows the JSON Web Signature (JWS) specification to generate the final signed token. It is generated by combining the encoded JWT Header and the encoded JWT Payload, and signing it using a strong encryption algorithm, such as HMAC SHA-256. The signature’s secret key is held by the server so it will be able to verify existing tokens and sign new ones.
$encodedContent = base64UrlEncode(header) + “.” + base64UrlEncode(payload);
$signature = hashHmacSHA256($encodedContent);
This gives us the final part of our JWT.
yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw

Security and Encryption with JWT

It is critical to use TLS/SSL in conjunction with JWT, to prevent man-in-the-middle attacks. In most cases, this will be sufficient to encrypt the JWT payload if it contains sensitive information. However, if we want to add an additional layer of protection, we can encrypt the JWT payload itself using the JSON Web Encryption (JWE) specification.
Of course, if we want to avoid the additional overhead of using JWE, another option is to simply keep sensitive information in our database, and use our token for additional API calls to the server whenever we need to access sensitive data.

Why the need for Web Tokens?

Before we can see all the benefits of using token authentication, we have to look at the way authentication has been done in the past.

Server-Based Authentication

Server-Based Authentication
Because the HTTP protocol is stateless, there needs to be a mechanism for storing user information and a way to authenticate the user on every subsequent request after login. Most websites use cookies for storing user’s session ID.
How it Works
The browser makes a POST request to the server that contains the user’s identification and password. The server responds with a cookie, which is set on the user’s browser, and includes a session ID to identify the user.
On every subsequent request, the server needs to find that session and deserialize it, because user data is stored on the server.


  1. Instruction
  2. Example
  3. Finish