Unit testing on laravel file downloading location - laravel

I am new to Laravel. I am writing unit testing on laravel for downloading a csv file. When I run the test case, I get assertResponseStatus as 200 and I need to open the created csv file and I am unable to find the location of downloaded file. How can I find the downloaded file.
This is the controller fuction
public function generateCsv(){
$list = $this->csvRepo->getDetails();
$heading = array(
'heading 1',
'heading 2',
'heading 3'
);
$this->csvRepo->generateCsv($heading,'csv',$list);
}
I need to know the location of downloaded file when run the test case

Assuming you are using the latest version of Laravel / PHP Unit you are able to use the following:
class ExampleFileDownload extends TestCase
{
public function fileDownloads()
{
Storage::fake('file');
// assuming we wanted to test like this:
$response = $this->json('POST', '/test', [
'file' => UploadedFile::fake()->image('testing.jpg')
]);
// Assert the file was stored – I believe this is the line you are looking for
Storage::disk('file')->assertExists('testing.jpg');
// Assert a file does not exist...
Storage::disk('file')->assertMissing('missing.jpg');
}
}
Let me know how you get on :)

Related

Laravel attach a non-physically saved file

I'm trying to find a way to attach a non-physical file to an email that's being made on the spot.
I'm using the following lines in my controller:
$columns = ['line1', 'line2'];
$rows = [
['line1' => 'first', 'line2' => 'second'],
['line1' => 'first', 'line2' => 'second'],
['line1' => 'first', 'line2' => 'second'],
];
Mail::to('email#email.com')->send(new ExportMail($columns, $rows));
And the following build function in the ExportMail class:
public function build()
{
$file = fopen('php://output', 'w'); // Tried w+ too
fputcsv($file, $this->columns);
foreach ($this->rows as $row) {
fputcsv($file, $row);
}
// I tried a couple of things:
return $this->view('emails.myTestMail')
->attach($file);
return $this->view('emails.myTestMail')
->attach(fopen($file, 'r'));
return $this->view('emails.myTestMail')
->attach(fopen('php://output', 'r'));
return $this->view('emails.myTestMail')
->attach(file_get_contents($file));
return $this->view('emails.myTestMail')
->attach(file_get_contents(fopen($file, 'r')));
return $this->view('emails.myTestMail')
->attach(file_get_contents(fopen('php://output', 'r')));
}
But none if it works so I'm beginning to question if there is a way to send an email with a file that is never physically saved.
You can attach file data directly with the attachData method documented here:
https://laravel.com/docs/9.x/mail#raw-data-attachments
I use this regularly to attach dynamically generated PDF files, for example.
You should be able to do something like this:
return $this->view('emails.myTestMail')
->attachData($yourCsvData, "attachment.csv");
Also, I think you want to look at how you are generating your CSV data. Right now using php://output the CSV data will be sent out to the browser immediately, not stored in a variable.
There are a couple ways you can solve this, output buffering being one, or using php://temp instead, or using one of many CSV libraries (like https://csv.thephpleague.com/). I put together a fully working example for you here using php://temp:
https://laravelplayground.com/#/snippets/aa5b6594-4493-4ca4-9d12-837c102b7cc5
Expand the rawAttachments attribute on that Message on the right, and you'll see the attached CSV file.

download file as unknown file in laravel

I want to download a pdf file from storage
public function show($free)
{
$dl = SingleFreeDownload::find($free);
return Storage::download($dl->file , $dl->title);
}
and this is the file storage code:
public function store(Request $request)
{
$file = $request->file('file')->store('uploads');
$single_download_page=[
'file' => $file, ];
SingleFreeDownload::create($single_download_page);
}
when I click on download button it downloads unknown file and it not open what is the problem?
First I wouldn't call the method which shall download a file show() I would rename it to download. Second I would check whether the file exists or not if it exists I would try to download it.
You can check whether it exists or not using this:
$exists = Storage::exists('myfile.jpg');
if ($exists) {
return Storage::download($dl->file , $dl->title);
}
Furthermore you should check wether your input contains the name file since you are doing this:
$file = $request->file('file')->store('uploads');
Your input needs to look like this:
<input name="file"...>
You should also show what this class does SingleFreeDownload.

Silverstripe 4 - SiteConfig module Image not working in template

I can't seem to get Silverstripe 4 to display images included in SiteConfig in my templates at all.I used to be able to just doe something like $SiteConfig.Logo and it would print out a automatic tag.
CustomSiteConfig:
<?php
use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\HeaderField;
use SilverStripe\AssetAdmin\Forms\UploadField;
use SilverStripe\Assets\Image;
use SilverStripe\ORM\DataObject;
use SilverStripe\CMS\Model\SiteTree;
class CustomSiteConfig extends DataExtension
{
private static $db = [
];
private static $has_one = [
'Logo' => Image::class,
'MobileLogo' => Image::class
];
private static $owns = [
'Logo',
"MobileLogo"
];
public function updateCMSFields(FieldList $fields)
{
$uploader = UploadField::create('Logo');
$uploader->setFolderName('Logo');
$uploader->getValidator()->setAllowedExtensions(['png','gif','jpeg','jpg']);
$fields->addFieldsToTab('Root.Main', [
HeaderField::create('hf2','Default logo'),
$uploader
]);
$uploader2 = UploadField::create('MobileLogo');
$uploader2->setFolderName('MobileLogo');
$uploader2->getValidator()->setAllowedExtensions(['png','gif','jpeg','jpg']);
$fields->addFieldsToTab('Root.Main', [
HeaderField::create('hf3','Mobile Logo'),
$uploader2
]);
}
}
But when I try in my template file. I get no URL
$SiteConfig.Logo
or
$SiteConfig.Logo().Link
etc
Nothing works?
A few things to check:
Verify that $SiteConfig is available as variable at that point in your template (Try using $SiteConfig.Title)
Verify that the extension is actually added to SiteConfig (do you see the CMS Fields?)
Did you add $owns later? run ?flush=1 again and re-save the SiteConfig *
Verify that both the SiteConfig and the File is published. (Save & Publish the SiteConfig twice, then check in the file manager if the file is published) **
[*] $owns is just a directive that when SiteConfig->doPublish() is called, it will also publish all files
[**] I've seen a bug that DataObjects don't actually publish files sometimes. Saving twice might work.
Just like Zauberfisch said, your image is probably not published. However, publishing the image after writing the owner can be tricky.
I usually through in this code
public function onAfterWrite()
{
parent::onAfterWrite();
if ( $this->LogoID ) {
$this->Logo()->doPublish();
}
if ( $this->MobileLogoID ) {
$this-> MobileLogo()->doPublish();
}
}
It's messy, I know, but it can save you a couple of hours. After saving you can remove it as the $owns hook will start to kick-in to all newly created objects.
We can Use This one
$SiteConfig.Logo.URL

yii shows error file not found at given location

i am trying to export excel file using eexcelview extention in yii
i am having following code with me
public function behaviors(){
return array(
'eexcelview'=>array(
'class'=>'extensions.eexcelview.EExcelBehavior'
),
);
}
and one more
public function actionTest()
{
// Load data
$model = Customer::model()->findAll();
// Export it
$this->toExcel($model, array(
'custid',
'custname'
),
'Test File',
array(
'creator' => 'Zen',
),
'Excel2007' // This is the default value, so you can omit it. You can export to CSV, PDF or HTML too
);
}
}
as given on toexcel extension documentation
i am having eecxcelview folder and EExcelBehavior file at extensions/eexcelview/EExcelBehavior.php location
but i am having following error while executing the code
Alias "extensions.eexcelview.EExcelBehavior" is invalid. Make sure it points to an existing PHP file and the file is readable.
please help me as I am new to yii and I am using yii 1.0 .
Try to referencing extension folder as "ext". Try the following:
'eexcelview'=>array(
'class'=>'ext.eexcelview.EExcelBehavior'
),

Laravel - Getting string from a flash

After processing form input, I redirect to a new route with some flash data:
return Redirect::route('work.index')
->with('flash', 'New work entry has been entered');
In the controller specified by work.index, I try to access the data
$flashed = Session:get('flash');
However, instead of a string, I end up with an array with two sub-arrays, old and new
Am I doing something wrong? Am I supposed to do this?
$flashed = Session::get('flash')['new'][0]
Store Data for next request
Session::flash('city', 'New work entry has been entered');
Retrieve Data from last request
$data = Session::get('city');
return Redirect::route('work.index')
->with('data', $data);
My Advice is to use Laracasts/Flash package that helps you to manage Flash messages in an easy way.
Here the GitHub repo: https://github.com/laracasts/flash
Installation
First, pull in the package through Composer.
"require": {
"laracasts/flash": "~1.0"
}
And then, if using Laravel, include the service provider within app/config/app.php.
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
And, for convenience, add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
And you can use it with:
Flash::info('Message')
Flash::success('Message')
Flash::error('Message')
Flash::warning('Message')
Flash::overlay('Modal Message', 'Modal Title')
Now in your theme you can easly integrate it with:
#include('flash::message')
NB:
Note that this package is optimized for use with Twitter Bootstrap.

Resources