Get response of custom artisan command in controller - laravel

I have created custom artisan command and trying to get response of it.
Here is the handle method of custom artisan command.
/**
* Execute the console command.
*
* #return string
*/
public function handle()
{
return 'Hello world';
}
Calling command from the controller
$result = Artisan::output('app:custom-command');
dd($result); // 0
dd(Artisan::output()); // ''
Expecting 'Hello world' in the controller.
Please note I want response not the output
i.e Not the output of $this->info('test.');

Commands don't return spesific variable they return an exit code.
if you get "hello world" from command;
command:
$this->info('Hello World');
controller:
Artisan::call('app:custom-command');
return Artisan::output();

First, please check these answers here:
Get response from Artisan call
Just to give you an insight, here a small thing you can do:
You can pass a variable by reference to the constructor of the Command class
As an example:
// File => UserController
$commandInstance = new DemoCommand($output);
$commandInstance->hanlde(); // Calling the related method manually
// Then in the DemoCommand Class #constructur method
public function __construct(&$output){
$this->output = $output;
}
// File => DemoCommand #handle Method
$result = ['a', 'b' ]; // ...
$commandInstance->setOutput($result);
You can also use session, Redis to save the data in memory and read it from the related class you need or store the output into a file or database...

Related

Laravel: Show output of a console command inside a migration?

I created a command to do some data manipulation on a very large database table and as it takes fair enough time to complete, i took the benefits of progress bar plus echoing some information on the console.
to automate stuff and reduce human errors, i want to call my command inside a laravel migration using programmatically-executing-commands style and it works but the problem is it wont print any output from corresponding command inside the console
i think i should pass the current Output-buffer that artisan:migrate is using to the Artisan::call function to make it work but had no luck to access it inside the migration
any suggestions?
Expanding on #ettdro's answer, the Artisan::call method has the following signature:
Artisan::call(string $command, array $parameters = [], $outputBuffer = null);
As you can see, the method accepts an output buffer as its 3rd argument. You can pass that output buffer to the method and the command logs will show up on the console.
Here's an example:
<?php
use App\Console\Commands\YourConsoleCommand;
use Illuminate\Database\Migrations\Migration;
use Symfony\Component\Console\Output\ConsoleOutput;
class SomeDbMigration extends Migration
{
public function up()
{
$output = new ConsoleOutput();
Artisan::call(YourConsoleCommand::class, ['--some-option' => true], $output);
}
public function down()
{
$output = new ConsoleOutput();
Artisan::call(YourConsoleCommand::class, ['--some-option' => false], $output);
}
}
You could use ConsoleOutput provided by Symfony to print out in the console after calling Artisan command. Make sure to use it in your desired .php file like so use Symfony\Component\Console\Output\ConsoleOutput;.
You could have something like this:
$output = new ConsoleOutput();
$exitCode = Artisan::call('your call');
if ($exitCode == -1)
$output->writeln("<bg=red;options=bold>Error occured while migration rollback " . "Exit code: " . $exitCode ."</>");
else {
$output->writeln("<bg=blue;options=bold>Rollbacked successfully! Exit code: " . $exitCode ."</>");
}
See in my example you can also add colors to your text, that could be useful to have better visuals on errors and success, see more at this link: https://symfony.com/search?q=ConsoleOutput

How i can get the variable data as string like a dd() function in Laravel?

I need to get the request data but i cant get ip, fullUrl and others with all() method (this only print input values), but when i use "dd(request())" this show me all data (i need the data what is printed with dd method, but like a string to save, withour the exception who print this data). Im debbuging my app so i need to save every request data in a log file, something like:
\Log::debug($request)
So,
You can use:
\Log::debug($request->toString());
or alternatively you can use
\Log::debug((string) $request);
The Laravel Request object comes from Illuminate\Http\Request which extends Symfony\Component\HttpFoundation which exposes the following code:
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = $k.'='.$v;
}
if (!empty($cookies)) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
__toString() is considered a magic method in PHP.
The __toString() method allows a class to decide how it will react
when it is treated like a string. For example, what echo $obj; will
print. This method must return a string, as otherwise a fatal
E_RECOVERABLE_ERROR level error is emitted.
You can read more about it in the official documentation.
I highly recommend to store just what you want from request data if you don't need all of them, however for both cases you can take a look at serialize and json_encode

No query results error using artisan with object instantiated in service provider

I have created a service provider which provides a class App\Path. This is loaded up through Eloquent using $request->getPathInfo()
$this->app->singleton(Path::class, function($app)
{
$request = $app->make(\Illuminate\Http\Request::class);
$path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
return $path;
});
The app works fine and as expected. However when I want to use Artisan I get the following error:
In Builder.php line 369:
No query results for model [App\Path] /
This prevents me from clearing caches, creating models etc. It seems that Laravel runs register() when running any artisan command and when this done, the request path is "/" which doesn't exist in the DB. Is there a better way to populate the Path object? The only way to solve this seems to add a dummy record for "/".
You can check whether the app is running from console and adjust its logic, for example:
$this->app->singleton(Path::class, function($app)
{
if ($app->runningInConsole()) {
return null;
}
$request = $app->make(\Illuminate\Http\Request::class);
$path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
return $path;
});

Getting Queued Jobs response Laravel 5.2

currently I have the following set up, a route that is calling a function in my controller that is in turn queuing a job.
//My Route
Route::get('/testJob', 'Controller#testJob');
//My Controller
public function testJob()
{
$job = (new testJob())->delay(5);
$this->dispatch($job);
}
//My job
public function handle()
{
require 'testAPICall.php';
// echo $response;
return $response;
}
//testAPICall.php
$response = 'this is the response';
//Queue After
Queue::after(function (JobProcessed $event) {
echo var_dump($event->data);
});
What I would like to be able to do, is access the response returned by the job in Queue::after, or alternatively, pass a callback into the queue to be execute after the job, again with access to the response from the job.
Is this something that is possible with Laravel Queues, and if so how would I go about this?
Cheers, Jack.
Queue::after() is a global callback, that will run after each job. So this might not what you want.
In your case, I would depend on Events/Listeners to be triggered after finishing the job.
public function handle(Mailer $mailer)
{
//Your code
event(new JobDone($data));
}
Please let me know if you need more details for implementation.
I have done something like yours that log a message "queue.txt" in laravel 5 "app" folder
This code I've got from a youtube video and not my code , but I have tested it successfully
First thing you have to code in "Routes.php" as below
Route::get('/',function()
{
//$queue = Queue::push('LogMessage',array('message'=>'Time: '.time()));
$queue = Queue::later(20,'LogMessage',array('message'=>'Time: '.time()));
return $queue;
});
class LogMessage{
public function fire($job,$data){
File::append(app_path().'/queue.txt',$data['message'].PHP_EOL);
$job->delete();
}
}
Then you can run your project folder using "php -S localhost:8888 -t public"
at the same time you must open a another terminal window in windows or linux environment and pointed to same folder and issue the command "php artisan queue:listen"
I think this will be helpful for you!

why my joomla controllers method is not getting executed

I have an ajax method which sends data to one of my controller but the method inside of my controller is not getting fired. Everytime the first method is getting executed on call. The controller looks as it follows
class TieraerzteControllerUploader extends JController
{
/**
* display task
*
* #return void
*/
function display($cachable = false)
{
require_once JPATH_COMPONENT_ADMINISTRATOR.'/helpers/upload.php';
$upload_handler = new UploadHandler();
//this one is going to be outputed
die();
}
public function locator(){
// I wait here for a dump, but is not happening
var_dump('test');
die();
echo '{"text":"John Smith","id":"433"},{"text":"Paul Sparks","id":"434"}';
}
}
I call the controller with the following url
/administrator/index.php?option=com_tieraerzte&task=uploader.locator&tmpl=component&q=search
even if I call the above url the result is the same
I think you are using wrong formated joomla url.
Try this url formate,u may call the controller
index.php?option=com_tieraerzte&view=uploader&tmpl=component&q=search
watch the difference between your url and my url.

Resources