Laravel doesn't find command - php

I make
php artisan make:command BackupDatabaseCommand --command="command:backupdb"
I also registered firmly
app\Console\kernel.php
protected $commands = [
\App\Console\Commands\BackupDatabaseCommand::class,
];
But even if you try to execute the command i get here
The system cannot find the path specified.
I want to know how to solve it

Your path is wrong Since you are already in App\Console directory there is no need to specify App\Console it should be this:
protected $commands = [
Commands\BackupDatabaseCommand::class,
];
here is the image from my working project
Thanks

To Create command
php artisan make:command BackupDatabaseCommand --command=command:backupdb
You can register command as:
protected $commands = [
'App\Console\Commands\BackupDatabaseCommand'
];
and you can run command using:
php artisan command:backupdb

Related

i could not run artisan schedule:run cron command at shared hosting

I want to achieve task scheduling in my laravel 5.8 project. For that, I have created a custom artisan command artisan send: credentials which send emails to specific users based on their status.
sendUserCredentials.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Mail\credentialsEmail;
use App\Models\userModel;
use Mail;
class sendUserCredentials extends Command
{
protected $signature = 'send:credentials';
protected $description = 'Credentials send Successfully!';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$users = userModel::select(["email","username","role","id"])->where("credentials","NO")->get();
foreach ($users as $key => $user) {
Mail::to($user->email)->send(new credentialsEmail($user));
userModel::where("id",$user->id)->update(["credentials"=>"SEND"]);
}
}
}
I added this command in kernel.php so that I can run this command using the laravel task scheduler.
kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\sendUserCredentials::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('send:credentials')
->everyMinute();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
so on my local server, everything works like a charm when I run this command php artisan schedule:run
but on the shared server when I run scheduler using the cron command *****/path/to/project/artisan schedule:run >> /dev/null 2>&1 it gives me an error like this
local.ERROR: The Process class relies on proc_open, which is not available on your PHP installation. {"exception":"[object] (Symfony\\Component\\Process\\Exception\\LogicException(code: 0): The Process class relies on proc_open, which is not available on your PHP installation. at /path/to/vendor/vendor/symfony/process/Process.php:143)
BUT when I run the artisan command directly *****/path/to/project/artisan send:credentials >> /dev/null 2>&1 using the cron job then there is no error and emails send successfully!
I am using laravel 5.8 and deployed my website on namecheap shared hosting. Following command help me to execute cron job properly:
*/5 * * * * /usr/local/bin/php /home/YOUR_USER/public_html/artisan schedule:run >> /home/YOUR_USER/public_html/cronjobs.txt
As namecheap allow minimum of 5 min interval, so above command will execute after 5 min and output will be displayed in a text file.
The Error
The Process class relies on proc_open, which is not available on your PHP installation.
is because of Flare error reporting service enabled in debug mode. To solve this please follow the steps shared below.
Add the File /config/flare.php and add the below content
'reporting' => [
'anonymize_ips' => true,
'collect_git_information' => false,
'report_queries' => true,
'maximum_number_of_collected_queries' => 200,
'report_query_bindings' => true,
'report_view_data' => true,
],
And Clear the Bootstrap cache with below command
php artisan cache:clear && php artisan config:clear
Most probably the issue will be solved. Otherwise check once this link

"php artisan key:generate" gives a "No application encryption key has been specified." error

I have a cloned laravel application but when I try to generate a APP_KEY via php artisan key:generate it gives me an error:
In EncryptionServiceProvider.php line 42:
No application encryption key has been specified.
Which is obvious because that is exactly what I'm trying to create. Does anybody know how to debug this command?
update: Kind of fixed it with this post laravel 4: key not being generated with artisan
If I fill APP_KEY in my .env file php artisan key:generate works. But a newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
For some reason php artisan key:generate thinks it needs a app_key when it doesn't. It won't do any other commands either, they all error "No application encryption key has been specified."
php artisan key:generate needs an existing key to work. Fill the APP_KEY with 32 characters and rerun the command to make it work.
Edit: A newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
Edit a year later:
The real problems lays in 2 added provider services. The boot() functions are badly written which causes the problem. Still not exactly sure why it doesn't work but I'll try and figure it out for somebody who may have the same problem later.
The two files in question
<?php
namespace App\Providers;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class ResponseServiceProvider extends ServiceProvider
{
public function boot(ResponseFactory $factory){
parent::boot();
$factory->macro('api', function ($data=null, $code=null, $message=null) use ($factory) {
$customFormat = [
'status' => 'ok',
'code' => $code ? $code : 200,
'message' => $message ? $message : null,
'data' => $data
];
if ($data instanceof LengthAwarePaginator){
$paginationData = $data->toArray();
$pagination = isset($paginationData['current_page']) ? [
"total" => $paginationData['total'],
"per_page" => (int) $paginationData['per_page'],
"current_page" => $paginationData['current_page'],
"last_page" => $paginationData['last_page'],
"next_page_url" => $paginationData['next_page_url'],
"prev_page_url" => $paginationData['prev_page_url'],
"from" => $paginationData['from'],
"to" => $paginationData['to']
] : null;
if ($pagination){
$customFormat['pagination'] = $pagination;
$customFormat['data'] = $paginationData['data'];
}
}
return $factory->make($customFormat);
});
}
public function register(){
//
}
}
<?php
namespace App\Providers;
use App\Http\Controllers\Auth\SocialTokenGrant;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Bridge\UserRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\PassportServiceProvider;
use League\OAuth2\Server\AuthorizationServer;
/**
* Class CustomQueueServiceProvider
*
* #package App\Providers
*/
class SocialGrantProvider extends PassportServiceProvider{
/**
// * Bootstrap any application services.
// *
// * #return void
// */
public function boot(){
parent::boot();
app(AuthorizationServer::class)->enableGrantType($this->makeSocialRequestGrant(), Passport::tokensExpireIn());
}
/**
* Register the service provider.
*
* #return void
*/
public function register(){
}
/**
* Create and configure a SocialTokenGrant based on Password grant instance.
*
* #return SocialTokenGrant
*/
protected function makeSocialRequestGrant(){
$grant = new SocialTokenGrant(
$this->app->make(UserRepository::class),
$this->app->make(RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}
}
php artisan key:generate is a command that create a APP_KEY value in your .env file.
When you run composer create-project laravel/laravel command it will generate a APP_Key in .env file, but when you checkout a new branch by git or clone a new project, the .env file will not include, so you have to run artisan key:generate to create a new APP_KEY.
You changed your question. In this case, you can try it.
php artisan key:generate
php artisan config:cache
If you don't have a vendor folder then,
1) Install composer dependencies
composer install
2) An application key APP_KEY need to be generated with the command
php artisan key:generate
3) Open Project in a Code Editor, rename .env.example to .env and modify DB name, username, password to your environment.
4) php artisan config:cache to effect the changes.
check your .env file. Is it exists?

Laravel create customs packages with commands

I am looking to make a generic appointment system in Laravel and I want to use that in my other projects.
Is there any way to achieve by creating custom commands? For example, php artisan make:auth creates a complete login, register, forgot and reset password functionality.
I want to do the same, like php artisan appoitment : make and it should create the models, controllers and database migrations in that Laravel installation
php artisan make:command {command name}. You can see {command name} file in app/console/commands directory.
change $signature to appoitment:make.
add your command class to app/console/Kernel.php commands list.
for example:
php artisan make:command AppoitmentCommand
In Kernel.php : $commands = [
AppoitmentCommand::class
];
php artisan //you can see all commands

Laravel custom command not working

I made a new command with:
php artisan make:console CrawlData
Then I changed two variables:
protected $signature = 'make:crawl';
protected $description = 'My crawling command';
The problem is that when I run:
php artisan make:crawl
It outputs:
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "make:crawl" is not defined.
You also need to register the command in the App\Console\Kernel class for it to be recognized:
protected $commands = [
...
\App\Console\Commands\CrawlData::class,
];
You can read more about that in the Registering Commands documentation.
Starting with Laravel 5.5 commands in app/Console/Commands are automatically registered.

Laravel running migrations on "app/database/migrations" folder recursively

So my migrations folder looks like this since I have dozens of tables it keeps things organized and clean:
migrations/
create_user_table.php
relations/
translations/
I'm trying to do a refresh all migrations and seed but it seems like I've run into a slight hiccup where I don't know the artisan command to run migrations recursively (i.e. run migrations in the relations and translations folders as well).
I've tried adding --path="app/database/migrations/*" however it spat out an error. Does anyone know the solution to this?
The only way to do it right now is to manually go through all the migrations. That is, you have to run the migration command on each of your subfolders:
php artisan migrate --path=/app/database/migrations/relations
php artisan migrate --path=/app/database/migrations/translations
However, what you can do is easily extend the artisan system to write your own migrate command that will iterate through all folders under the migrations folder, create these commands for you and run them.
You can also simply write a shell script if you don't want to get into doing this via artisan
Edit: for Laravel >= 5.0, the correct commands to migrate migration files in sub directories would be:
php artisan migrate --path=/database/migrations/relations
php artisan migrate --path=/database/migrations/translations
This add to boot method in AppServiceProvider
$mainPath = database_path('migrations');
$directories = glob($mainPath . '/*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);
$this->loadMigrationsFrom($paths);
Now you use can php artisan migrate and also php artisan migrate:back
You can also use a wildcard, like so:
php artisan migrate --path=/database/migrations/*
You can use the following command to do this recursively:
php artisan migrate --path=/database/migrations/**/*
**/* is also known as the globstar
Before this works you must check if your bash supports the globstar.
You can do this by executing shopt and checking for globstar.
Globstar is supported by default by most server distributions but might not work on MAC.
For more on globstar see: https://www.linuxjournal.com/content/globstar-new-bash-globbing-option
In Laravel 5 the database folder sits alongside the app folder by default. So you could run this to migrate a single folders migrations:
php artisan migrate --path=/database/migrations/users
You can try this package nscreed/laravel-migration-paths. By default all sub directories inside the migrations folder will be autoloaded. Even you can add any directories very easily.
'paths' => [
database_path('migrations'),
'path/to/custom_migrations', // Your Custom Migration Directory
],
Don't need any special command just the generic: php artisan migrate will do your tasks.
I rewrote the MigrationServiceProvider:
- registerResetCommand()
- registerStatusCommand()
- registerMigrateCommand()
There you can register your own commands:
class MigrateCommand extends Illuminate\Database\Console\Migrations\MigrateCommand
After that you just need to extend youd directories:
protected function getMigrationPaths()
Or you just register the paths on application boot.
I've already done my solution before I knwewd about '$this->loadMigrationsFrom'.
A Simple solution is to create an Artisan Command for example (migrate:all),
then inside handle function define migrate command for each sub directories as mentioned bellow.
Artisan::call('migrate', [
'--path' => '/database/migrations/employee'
]);
Only relative path works for me (in Laravel 5.7):
php artisan migrate --path=database/migrations/your-folder-with-migrations
This works at laravel 8
php artisan migrate --path=database/migrations/tenant
It is a not a "direct" solution but i suggest you to look at Modularity into your laravel project.
Modules can segment your application in several smaller "folders" and bring migration, seeds, classes, routes, controllers, commands together in easily maintainable folders.
This package is a good start : https://github.com/pingpong-labs/modules
No changes are necessary, whenever you need it, use this command:
php artisan migrate --path=database/migrations/*
If you want a shortcut, you can include that in your composer.json:
"scripts": {
"migrate": [
"#php artisan migrate --force --path=database/migrations/*"
]
}
Then just use composer migrate in the terminal.
add in app/Providers/AppServiceProvider.php the path of your migration folder, you can add a string or an array
public function register()
{
$this->registerMigrations();
}
protected function registerMigrations()
{
return $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/**/*');
}
A Simple Laravel solution is to create a gulp task (say migrate-others).
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var shell = require('gulp-shell')
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
// Our Task
gulp.task('migrate-others', shell.task([
'php artisan migrate --path=/app/database/migrations/relations',
'php artisan migrate --path=/app/database/migrations/translations',
]));
Now you can simply call
gulp migrate-others
Here you go!
function rei($folder)
{
$iterator = new DirectoryIterator($folder);
system("php artisan migrate --path=" . $folder);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
rei($folder . $fileinfo->getFilename() . '/');
}
}
}
rei('./database/');

Categories