Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Related tags

Laravel artisan-api
Overview

Artisan Api


Packagist PHP Version Support GitHub Packagist Version GitHub branch checks state Packagist Downloads GitHub all releases tests-passed-green GitHub repo size

Linkedin URL

There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API solution for you.

You are able to run Artisan commands by REST APIs easily.

Table of contents

Get Started

To use this package, you should install it alongside Laravel v9.5 and PHP v8.0 or higher.

you can install it via Composer package manager:

composer require aariow/artisan-api --dev

Although, Artisan-Api has production decetor itself, it is possible to install it globally.

Endpoints

As its name explains, all commands are available via HTTP with POST method. All commands will be generated as routes and integrated into Laravel Routing system. You only need to send a POST request and follow the signature, like other REST API endpoints.

There are two kinds of commands; one is normal commands like php artisan list or php artisan cache:clear, and the second form is GeneratorCommands which tend to create files within your application like make:model and make:migration. These kind of commands have different purposes, you should follow diffenerent convention.

GeneratorCommand are instance of Illuminate\Console\GeneratorCommand that extends Illuminate\Console\Command class.

All commands existed by default or created by you will be discovered automatically and you do not have to do anything manually. Thus, their endpoints will be generated dynamically to your application. So if you delete/add any command class, there is no reason to worry.

Routes

Let's dive into using endpoints:

Routes are generated with the following format:

https://domain.com/artisan/api/{command}/{subcommand}?args=key1:value1,key2:value2&options=opt1:value1,opt2


So the above endpoint will be translated to:

php artisan command:subcommand value1 value2 --opt1=value1 --opt2


And for Generator commands the endpoint is:

https://domain.com/artisan/api/{command}/{subcommand}/{name}?args=key1:value1,key2:value2&options=opt1:value1,opt2

Pay attention that there is a name variable. As all Generator commands need an argument called name, this needs to be specified by what you desire.


Command Examples:

php artisan list

will be translated to:

https://domain.com/artisan/api/list


and this:

php artisan cache:forget myCachedKeyName

will be translated to:

https://domain.com/artisan/api/cache/forget?args=key:myCachedKeyName


Another one:

php artisan optimize:clear -v

will be translated to:

https://domain.com/artisan/api/optimize/clear?options=v


A Generator one:

php artisan make:model MyModel --controller -f

will be translated to:

https://domain.com/artisan/api/make/model/MyModel?options=controller,f

Options with more than one character will be translated to --option.

Responses

After calling an endpoint, you will receive a Json response.

Successful

When everything works perfectly: status : 200 OK

{
  ok: true,
  status: 200,
  output: "Output of the command, given by Artisan"
}
Not found

When inputed command is not found by application: status : 404 Not Found

{
  ok: false,
  status: 404,
  output: "Command "command:subcommand" is not defined."
}
Invalid Arguments format

When arguments are given by an invalid format: status : 500 Server Error

{
  ok: false,
  status: 500,
  output: "Argument(s) 'key:value' given by an invalid format."
}
Invalid Options format:

When options are given by an invalid format: status : 500 Server Error

{
  ok: false,
  status: 500,
  output: "Options(s) 'key:value' given by an invalid format."
}

Forbidden routes

You might want to limit access to some critical commands like db:seed. Artisan-Api has thought about it and make those commands inaccessible by client. To specify forbidden commands, you are encouraged to add them within config/artisan.php file:

return [
    ...,

    'forbidden-routes' => [
        'clear-compiled',
        'tinker',
        'up',
        'down',
        'serve',
        'completion',
        '_complete',
        'db*', // all `db:seed` and `db:wipe` will be inaccessible
        '*publish' // like `vendor:publish`
    ]
];

Whenever client wants to access these commands by endpoints, it will be given a 404 NOT_FOUND HTTP response.

Authentication

All enpoints will be generated under the api middleware of Laravel and prevented by built-in authnetication system, mostly with Sanctum and API tokens.

Configurations

As mentioned before, there is a configuration config/artisan.php file. You are free to modify specified values as you desire.

API Prefix and HTTP Method

Here, it is possible to change default API prefix and customize it as necessary. In addition you can access endpoints with any HTTP method as you set.

return [
    ...
    'api' => [
        'prefix' => "/artisan/api",
        'method'    => 'POST', // or ['POST', 'PUT']
    ],
    ...
];

Auto Run

For some reason and mostly on production mode, you do not want to allow commands to be executed by HTTP request. To prevent this behavior, set that auto-run to false:

return [
    ...
    'auto-run' => false,
    ...
];

This prevents not to load package's service-provider (ArtisanApiServiceProvider) by default.

Middlewares

There are two middlewares in Artisan-Api.

CheckEnvMode middleware exists to abort requests while in production environment.

AbortForbiddenRoute middleware exists to throw 404 NOT_FOUND status code while accessing to forbidden routes.

Useful tips

;)

Todo

  1. It'd better be done to take args and options in query string, to be array.
    • Like: `?arg[key1]=value1&arg[key2]=value2 (it is a more standard way to deal with query string values)
  2. Implement a way to deal with interactive commands like tinker (maybe can be implemented by socket)
  3. Make response more readable for users, (remove "\n", ...)
You might also like...
Deploy and execute non-PHP AWS Lambda functions from your Laravel application.

Sidecar for Laravel Deploy and execute non-PHP AWS Lambda functions from your Laravel application. Read the full docs at hammerstone.dev/sidecar/docs.

Laravel 4.* and 5.* service providers to handle PHP errors, dump variables, execute PHP code remotely in Google Chrome

Laravel 4.* service provider for PHP Console See https://github.com/barbushin/php-console-laravel/releases/tag/1.2.1 Use "php-console/laravel-service-

a Laravel package help you to execute more effective databases queries.
a Laravel package help you to execute more effective databases queries.

Laravel Query Helper Laravel Query Helper was developed for laravel 7.2+ to help you optimizing sql queries, this package will contain all advanced sq

This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.
This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.

Laravel Mobile Verification Introduction Many web applications require users to verify their mobile phone numbers before using the application. Rather

Log requests and group together for aggregated statistics of route usage
Log requests and group together for aggregated statistics of route usage

Log Laravel route usage statistics Log Laravel requests and responses for statistical purposes and optionally aggregate by hours/days/months for minim

Make requests to the Shopify API from your Laravel app
Make requests to the Shopify API from your Laravel app

Make requests to the Shopify API from your Laravel app The signifly/laravel-shopify package allows you to easily make requests to the Shopify API. Ins

Laravel magical helpers such as Controllers / Requests / Models

Laravel Magic provides Abstract Controller, Model, generic Request, Traits, Exceptions and various middlewares in order to generate very easily and quickly API resources from scratch.

📦 Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.
📦 Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

This package is to add a web interface for Laravel 5 and earlier Artisan.
This package is to add a web interface for Laravel 5 and earlier Artisan.

Nice Artisan This package is to add a web interface for Laravel 5 and earlier Artisan. Installation Add Nice Artisan to your composer.json file : For

Comments
  • Third-party console commands will not load after generating routes

    Third-party console commands will not load after generating routes

    We installed laravel/dusk and laravel/breeze beside ArtisanApi. Once ArtisanApi provider calls the method router()->generate() other third-party commands will not be shown in artisan list.

    There should not be something wrong with router()->generate() itself. The problem occurs when ArtisanApiManager (package's instance) is being called using app('artisan.api') or $this->app->make('artisan.api') within package's service provider, even without calling router()->generate().

    ArtisanApiServiceProvider.php:

    
        public function boot()
        {
            if ($this->shouldBeLoaded()) {
    
                $this->setMiddlewares();
            }
        }
    
            /**
         * @inheritDoc
         * 
         * We have to initialize the package to feed the commands after
         * loading all providers by Laravel
         */
        public function callBootedCallbacks()
        {
            $this->app->call(
                function () {
                    $this->app->make('artisan.api')
                        ->init( CommandsIterator::getInstance() )
                        ->router()->generate();
                }
            );
        }
    
    
    bug good first issue 
    opened by arfar-x 4
Releases(v1.2.1-beta)
Owner
Alireza
PHP/Laravel back-end developer
Alireza
📝 Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 148 Nov 29, 2022
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

Matt Brunt 6 Dec 17, 2022
This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.

Laravel Nova tool for running Artisan & Shell commands. This Nova tool lets you run artisan and bash commands directly from nova. This is an extended

Artem Stepanenko 17 Dec 15, 2022
A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands.

artisan.page A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands. Generation The generation of the manifest files is d

James Brooks 284 Dec 25, 2022
Laravel API architecture builder based on artisan commands.

??‍?? API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

Krševan Lisica 1 Jan 16, 2022
A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

Andrew Huggins 94 Nov 22, 2022
Dispatch Laravel jobs via Artisan

This package can register jobs as Artisan commands. All you need to do is let your job implement the empty ArtisanDispatchable interface.

Spatie 135 Nov 7, 2022
Dashboard to view your http client requests in laravel application

Laravel Blanket is a package with wraps laravel http client requests and provide logs for request and response, also give option to retry any request from dashboard and more...

Ahmed waleed 215 Dec 29, 2022
Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.

REST API Response Builder for Laravel Master branch: Development branch: Table of contents Introduction Why should I use it? Usage examples Features E

Marcin Orlowski 614 Dec 26, 2022
Backend application using Laravel 9.x REST APIs for games topup from digiflazz.com and payment gateway using xendit.co

TOPUP - Laravel 9.x REST API Documentation is still on progress. For now, you can fork this postman collection Installation Clone this project git clo

Muhammad Athhar Kautsar 46 Dec 17, 2022