How to use composer, artisan ...(Laravel) php commands manually - php

I have one problem I have no ssh access to the server, so I cannot use php artisan, composer and other commands.
As I can quess they do nothing other than modifying files or just copying php src files to specific directories.
In order to understand that process better and because of no access via ssh to the server I am looking for tutroial, manual or an article how can I perform this commands manually.
For example I need to execute
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
What should I do in this case, it would be grate to find some document describes what should I do manually to get the same result.

Laravel provides a handy Facade for artisan commands.
Just use Artisan::call('your-command') from where you need.
Example:
Route::get('artisan-command/{command}', function($command) {
Artisan::call($command);
});
Your URL looks like this: http://yourhost.com/artisan-command/db:seed
More specific for your use-case:
Route::get('vendor-publish/{provider}', function($provider) {
Artisan::call('vendor:publish', ['provider' => $provider]);
});
And the URL: http://yourhost.com/vendor-publish/Tymon\JWTAuth\Providers\JWTAuthServiceProvider
Reference: Artisan Console in the Laravel Docs

You can execute command lines from your app. You can do something like this:
Route::get('execute/my/command', function(){
exec("php path/to/your/project/artisan your-command",$resultLines);
Foreach($resultLines as $resultLine){
echo $resultLine;
}
});
First exec property is your command and second is variable to save the result.
I hope that help you

Related

Laravel run package artisan command in controller

I need to run this command when user change something in translation file
php artisan export:messages-flat
I need to add it in may controller
so I'm using this code
\Artisan::call('export:messages-flat');
but it return error saying that
The command "export:messages-flat" does not exist.
but when I
php artisan list
it's in the list
I also try to run other command
\Artisan::call('cache:clear');
and it works
this is the package I'm using link
kindly help me, sorry for may poor english
The package only allows you to run the commands from the CLI. You can see from the source code, they only register the Artisan commands if the application is running from the console.
As an alternative, you can call ExportLocalization::export()->toFlat() according to their documentation.

PHP Script - How to use php artisan command in my script?

I'd like to create a php script which connects to a mysql server, makes changes on a database and runs a php artisan command.
The first part I have figured out (mysql connection) but is it possible to just put (for example):
php artisan snipeit:ldap-sync --location_id=1
into my script and it will run the command, or am I missing something here?
I'd appreciate it if you could send me into the right direction wtih this. Thank you.
You can use Artisan::call().
Artisan:call('snipeit:ldap-sync', [
'--location_id' => 1
]);
It can also take a second parameter to specify an array of command parameters.
For more information, see Programmatically Executing Commands.
You can call artisan command from code like this:
Artisan::call('cache:clear');

Is it possible to create custom npm run commands for Laravel?

Laravel has the following built-in npm run commands (among others):
npm run install
npm run watch
Is it possible to create custom npm run commands to run custom PHP scripts? For example, I want to create a command called npm run csv that will run a PHP script that imports a bunch of CSV data into a database.
Thanks.
Edit: After asking the question and seeing a lot of the responses, it has become overwhelming obvious that writing a php artisan command is probably the better way to go. As such, that's what I will do.
Thank you all for your responses. As for why I didn't ask that question, it's quite simple: I didn't know that that was a better approach. I'm still new to Laravel and learning. Thanks.
At first, you must write Artisan Console Command. Then you could run it using npm. But this is not a recommended way. you can run any artisan command like:
php artisan inspire
If you want to run this with npm just add this command in the package.json's script. For example:
{
"scripts": {
"inspire": "php artisan inspire"
}
}
Then run the command like this:
npm run inspire
It should be cleaner to create your own artisan command.
See https://laravel.com/docs/5.7/artisan#writing-commands
Then put your csv import code inside the handle() method.
You will just have to run : php artisan import-csv or something like
I love this side of Laravel. From what you are trying to achieve, may I advise on custom artisan commands? :)
https://laravel.com/docs/5.7/artisan
Recommend the reading, it is great for what you are looking :D
There's no need to use NPM to call PHP! Why not just create your own executable?
Using Laravel, there is a command system, so you can make your own artisan commands. But if you want something simpler, you can do this:
Example. I create a file in my project called bin/do_stuff
#!/usr/bin/env php
<?php
echo "Easy as that!\n";
Then make it executable:
chmod +x bin/do_stuff
Then you can run it with ./bin/do_stuff! Not hard at all! Now you can also pass arguments like so:
./bin/do_stuff--option1=value1 --option2
With or without values. To do this, we add the following:
foreach ($argv as $arg)
{
preg_match('/\-\-(\w*)\=?(.+)?/', $arg, $value);
if ($value && isset($value[1]) && $value[1])
{
$options[$value[1]] = isset($value[2]) ? $value[2] : null;
}
}
Great for in cron jobs and back end stuff. Give it a try!

Laravel Artisan - reload .env variables or restart framework

I'm trying to write a command as a quickstart to build a project. The command asks for input for database details and then changes the .env file. The problem is that the command needs to do some Database queries afterwards, but the .env variables are not reloaded.
My question would be, is there a way to reload or override .env variables runtime. And if not, is there a way to call another Artisan command freshly, so framework bootstraps again?
In my command I tried doing $this->call('build:project') in my actual command, but even in the second call the variables are not reloaded.
Is there a way to achieve this without making the user manually call multiple commands?
Thanks!
i had the same problem with reloaded .env variables, and i fixed it with this command line which allow you to clear the configuration :
php artisan config:clear
Hope that helped. Regards.
Laravel uses config files which take data from .env file. So, what you can do is to override configuration values at runtime:
config(['database.default' => 'mysql']);
Try to clear cache it helped me (couldn't ssh into the server)
Is there a {app route}/bootstrap/cache/config.php file on the production server? Delete it.
This helped me
As OP I'm trying to bootstrap a Laravel project build by running console command and asking for the database credentials in the middle of the process.
This is a tricky problem and nothing I read was able to fix it : reset config, cache, Dotenv reload, etc... It seems that once the console command / operation is initialized the initial database connection is kept all over until the end.
The working solution I found is to bypass, after database modification are done, this cached state by using native shell exec command and passing the php artisan command as parameter :
passthru('php artisan migrate');
So, the order will be :
php artisan project:build (or whatever is your console command)
prompt the user for database credentials
replace values in .env file (your search & replace algorythm)
run php artisan config:cache
passthru('php artisan migrate'); ro run your migrations
shell_exec would do the same but in silent mode while passthru will return the output generated by console.
https://www.php.net/manual/en/function.passthru.php
Done successfully on Laravel 8.52

Laravel setup, trying to have cronjob call a function within php laravel file

Original Post
Good evening folks. I have a laravel setup and I'm trying to have a cronjob execute a php function to a file within the laravel project directory.
I am getting class and name space errors when I try to do something like this:
<?php
require_once('../laravel/app/Http/Controllers/NotificationsController.php');
and then calling the processQueuedNotifications() function.
This of course gives me errors, what is the correct way to call my function within the laravel directory? I need to call this function as this function has all the correct namespaces and extended controllers necessary to execute the function properly.
Update 1:
Thanks to #michael, I've been made aware of a component in Laravel called commands.
So I ran this code:
php artisan make:console processQueuedNotifications
and it created some files in the console directory.
Currently exploring on what to do next.
After checking out the Events class which the kernel.php file makes use of, I noticed that this class provides an easy to use interface for me to create cron jobs on the fly. Am I correct in think so?
I notice there is not function to run a cron job every minute, is it safe to edit the Events class file without it being overwritten by future make:console commands, or laravel updates?
I saw this code in the kernel.php file:
$schedule->command('inspire')
->hourly();
So is this the place you wanted me to add my function? as I notice that the inspire function is something automatically created for me to understand what's going on?
So I would write,
$schedule->command('processQueuedNotifications')
->everyMinute();
//Providing it's safe to edit the Event's class or figure out a clean way of doing so without my code being deleted in the future on Laravel updates.
A very convenient way is to use laravels console component. You can create a new command by issuing
php artisan make:console
And find it thereafter in your app/console directory. Make sure to enable the command in the Kernel.php file once created.
Simply call your class or whatever you want to run via cron from inside the command. The console command itself is callable via cli just as you would run one of laravels php artisan ... commands. You can set this in the file created for you. For example, you can then call the file from everywhere you want with
/usr/bin/php /path/to/file/artisan my:command
You can set options and arguments if you need to.
Here's the documentation: http://laravel.com/docs/5.0/commands / http://symfony.com/doc/current/components/console/introduction.html
There's an array in kernel.php you need to register your class (include the namespace) in. After that it is callable via cli. For a start, have a look on arguments and options you can initialize in case you need to make different requests on your controller class. (The filename you have chosen for your console command, is an argument. You can make them required or optional for your own commands. )
Within your file, you can create them by simply creating an array in the appropriate method with these values:
[$name, $mode, $description, $defaultValue]
have a look at the docs or Jeffrey's laracasts, they are very good.
To only call your class from the console command, it's enough to name your command in the above section of the file and call you controller like
(new namespace\controller)->method();
What you can do in your code, after your update, 2 choices :
Dispatching directly the command from your code using the Bus facade
first import it using the
use Illuminate\Support\Facades\Bus;
then in your code
Bus::dispatchNow(new YourCommandClass);
(don't forget to import your command class)
Dispatch it for queue process using the same bus facade:
(still importing the same way)
Bus::dispatch(new YourCommandClass);
(Note that in that case, you'll need to have the following command run by your cron job :
php artisan queue:listen
it can handle several options such as the --tries=X where is is the number of tries etc
Generally speaking, you can get more info from commands typing php artisan my:command -h

Categories