How to create migrate,controller,model using laravel artisan commands ?

 

In laravel you can create Controller,Events,Listners and many more file either manually or using artisan command. In this tutorial we will discuss how we can create these file using Artisan command. Artisan is a Command Line Interface(CLI) tool. It provides a lots of helpful commands which we will discuss now.You can call the artisan command from command line or from controller or from route file.Sometimes in shared hosting the service provider does not allow to work on command line so in that case you can call the command from either route file or controller file.Now we will see different method to call Artisan command.

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

2)Call Artisan Command from Controller
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.

3)Call Artisan Command from Route
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.

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories