Where does the console command save exported file - php

I'm using Laravel 5.8 and I tried creating a custom command like this:
php artisan make:command app exportappresults
And the Command goes like this:
protected $signature = 'app:exportappresults';
protected $description = 'Export App Exam Result Into Excel';
public function __construct()
{
parent::__construct();
}
public function handle()
{
return Excel::download(new TavanmandAppUserExamExport,'userexamlist.xlsx');
}
So as you can see I have used Laravel Excel and tried exporting data into Excel file.
Note that this code works fine in the Controller and can properly export an Excel file.
But now I don't know where does the exported excel file from the DB goes when I use the Console Command.
So if you know, please let me know...
Thanks.

Excel::download is used in HTTP controllers, to pass exported data to HTTP response. If you need to store file on disk, use Excel::store instead:
public function handle()
{
Excel::store(new TavanmandAppUserExamExport, 'userexamlist.xlsx');
}
File will be stored in default storage (disk), configured in laravel's config/filesystems.php, by default it's ./storage/app.
Also you may specify another disk as third argument of Excel::store method, see Storing exports on disk

Related

Export big Excel with Laravel Excel 3.1

Hello I need help with Laravel Excel 3.1 with Laravel 7.
I have to export an excel with arround 300,000 records o more and download or save in public folder to download...
So when i do it with this plugin, localhost works fine. But in the server it shows an error 500.
I set memory limit = -1 and time execution = 1800.
it takes time to appear error 500 arround 10min or less.
This is my code:
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
class ProductsExport implements FromQuery
{
protected $filters;
use Exportable;
function __construct($filters) {
$this->filters= $filters;
}
public function query()
{
return Product::query()
->where($this->filters)
->orderby('name');
}
}
Controller
(new ProductsExport($filters)->queue('products.xlsx');
return back()->withSuccess('Export started!');
In excel.php I just configured chunk_size to 5000. I don't know what else I need to configure here
I know that i need to use queue for big data, and i used it, but i dont know what else to do.

Problem in reading file from server using laravel excel

I am trying to read an excel file from server. I want to get the data and turn it into an array.
Earlier I tried converting excel into an array and I succeeded. I used the following code.
$data = Excel::toArray(new Import, request('file') , 'public');
My import Class was
class Import implements ToModel,WithCalculatedFormulas
{
use Importable;
/**
* #param Collection $collection
*/
public function model(array $row)
{
}
}
And it was working perfectly. Now instead of submitting the file by a form; I need to read it from server. So I changed the code to,
$data = Excel::toArray(new Import, $file_url , 'public');
But now it is giving me error like below. (I changed the url to post here)
File not found at path:
http:/XXXX.YYY.com/temp_upload/1581488988_test.xlsx
I checked my server. The file is indeed there. Even, when I try to browse the URL it is downloading the correct file. But it isn't being read.

Mock file in Storage to download in Laravel

Is there a way to mock a file using Laravels Storage::fake() method?
I have used https://laravel.com/docs/5.7/mocking#storage-fake as a base for my tests, which works fine for uploads. But my download tests are ugly as I have to run my upload route first every time with a mock upload UploadedFile::fake()->image('avatar.jpg'). Is there a way to skip that part and mock the file to exist directly in the fake storage system?
public function testAvatarUpload()
{
Storage::fake('avatars');
// This is the call I would like to change into a mocked existing uploaded file
$uploadResponse = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
// Download the first avatar
$response = $this->get('/download/avatar/1');
$response->assertStatus(200);
}
I might be late here. but wanted to help others visiting this question to give an idea of implementing it.
Here is a sample with some assertions.
<?php
namespace Tests\Feature\Upload;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class SampleDownloadTest extends TestCase
{
/**
* #test
*/
public function uploaded_file_downloads_correctly()
{
//keep a sample file inside projectroot/resources/files folder
//create a file from it
$exampleFile = new File(resource_path('files/test-file.png'))
//copy that file to projectroot/storage/app/uploads folder
Storage::putFileAs('/uploads', $exampleFile, 'test-file.png');
//make request to file download url to get file
$response = $this->get("/files/file/download/url");
//check whethe response was ok
$response->assertOk();
$response->assertHeader('Content-Type', 'image/png')
//check whether file exists in path
Storage::assertExists('/uploads/test-file.png');
//do some more assertions.....
//after test delete the file from storage path
Storage::delete('uploads/test-file.png');
//check whether file was deleted
Storage::assertMissing('/uploads/test-file.png');
}
}
Yes, you can use fake file storage feature of Laravel (mocking):
use Illuminate\Http\UploadedFile;
$file = UploadedFile::fake()->create('filename.ext', $sizeInKb)->store('filename.ext');
If you want to create a text/csv file with a specific content you can use this:
use Illuminate\Http\UploadedFile;
$header = 'a,b,c';
$row1 = 'x,y,z';
$row2 = 's,f,t';
$row3 = 'r,i,o';
$content = implode("\n", [$header, $row1, $row2, $row3]);
$file = UploadedFile::fake()->createWithContent('filename.ext', $content)->store('filename.ext');
You can find this methods definitions in Illuminate\Http\Testing\FileFactory
You could just create a new file directly or copy a specific test file for example:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// for simple text files or if the content doesn't matter
Storage::disk('avatars')->put('avatar.jpg', 'some non-jpg content');
// if you need a specific file for your test
$file = new File(base_path('tests/resources/avatar.jpg'));
Storage::disk('avatars')->putFileAs('/', $file, 'avatar.jpg');
The latter function will take the $file and copy it under the given name avatar.jpg to the given directory / on the disk avatars. You can read more about it in the official documentation.
What you could use to solve that problem is fixtures. Laravel's testing framework is essentially PHPUnit, so I see no reason why it would not work.
define your test like so:
use Tests\TestCase;
class ExampleTest extends TestCase {
protected function setUp() {
parent::setUp();
Storage::fake('avatars');
$uploadResponse = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
}
protected function tearDown() {
parent::tearDown();
}
public function testAvatarUpload() {
// Download the first avatar
$response = $this->get('/download/avatar/1');
$response->assertStatus(200);
}
}
setUp and tearDown get called, respectively, before and after each test in the class. So, before each test method, setUp will wipe the avatars fake disk and run the request. As there is nothing to do after a test (since Storage::fake() replaces the disk if it already exists), the method is empty; I left it here purely to make the example complete.
There's some pretty good documentation on here about this feature of PHPunit.
Regarding putting the file on there, once you have your setUp working correctly, there's nothing stopping you from throwing the file on it.

Generating an XML Sitemap in Laravel 5

I have a laravel application that is still in the development stages. I am currently trying to generate a sitemap for the application using Spatie\Sitemap\SitemapGenerator but my code isn't working. This is my sitemap code in a file called GenerateSiteMap.php:
<?php
use Spatie\Sitemap\SitemapGenerator;
class GenerateSiteMap
{
public function generateSite()
{
$generator = SitemapGenerator::create('http://127.0.0.1:8000/')->writeToFile('sitemap.xml');
return $generator;
}
}
It doesn't give me any errors when I run it, it just doesn't do anything. Any idea how I can fix it?
If your file is at public folder you need to add public_path
$generator = SitemapGenerator::create('http://127.0.0.1:8000/')->writeToFile(
public_path('sitemap.xml'));
otherwise it might be a permission issue

yii console command custom help information

I created file commands/TestCommand.php in my yii-powered project:
class TestCommand extends CConsoleCommand
{
public function actionIndex()
{
echo "Hello World!\n";
}
}
And it's became visible via yiic:
Yii command runner (based on Yii v1.1.14)
Usage: yiic.php <command-name> [parameters...]
The following commands are available:
- message
- migrate
- shell
- test <<<
- webapp
To see individual command help, use the following:
yiic.php help <command-name>
If I am trying to get some help information about this console command:
php yiic.php help test
I see default text:
Usage: yiic.php test index
How can I write my TestCommand class which will show my help information? Is it a some public field or special method which return help text? I need something like that:
php yiic.php help webapp
Result like I need:
USAGE
yiic webapp <app-path> [<vcs>]
DESCRIPTION
This command generates an Yii Web Application at the specified location.
PARAMETERS
* app-path: required, the directory where the new application will be created.
If the directory does not exist, it will be created. After the application
is created, please make sure the directory can be accessed by Web users.
* vcs: optional, version control system you're going to use in the new project.
Application generator will create all needed files to the specified VCS
(such as .gitignore, .gitkeep, etc.). Possible values: git, hg. Do not
use this argument if you're going to create VCS files yourself.
You can override the default getHelp method to implements your help!
It must return a string that is the help text.
Provides the command description. This method may be overridden to return the actual command description.
Here is the default method:
public function getHelp()
{
$help='Usage: '.$this->getCommandRunner()->getScriptName().' '.$this->getName();
$options=$this->getOptionHelp();
if(empty($options))
return $help."\n";
if(count($options)===1)
return $help.' '.$options[0]."\n";
$help.=" <action>\nActions:\n";
foreach($options as $option)
$help.=' '.$option."\n";
return $help;
}
You can also override the default getOptionHelp method that is called in getHelp
Provides the command option help information. The default implementation will return all available actions together with their corresponding option information.
Source

Categories