Laravel Scout and Elastic Search Don't Work in Tests - php

I have elastic search working when not in a testing environment. However when I create a model in a test for some reason it does not work. I have tried running it with the queue and without the queue. I can see that the job gets created and that the job runs before making the call. However, I am able to pull things that are already in the database in the test code. Any ideas why it would not work in testing?
This is my test code
$user = $this->newLoggedInUser();
$invoice = factory(App\Invoice::class)->create(['account_id' => $user->account_id]);
$this->get($this->url() . '?q=' . $invoice->title, $this->userAuthHeader($user))
->seeJson([
'Title' => 'Invoice: ' . $invoice->number . ($invoice->title ? ' - ' . $invoice->title : ''),
'Description' => 'Customer: ' . $invoice->customer->name,
'Type' => 'Invoice',
])
->assertResponseStatus(200);

I found that I had to add a slight delay to the get call as the index was not updated before the call was made. So I added sleep(1) and that fixed it. Also, I found that it is best to specify a separate index for the testing environment in the config.
$user = $this->newLoggedInUser();
$invoice = factory(App\Invoice::class)->create(['account_id' => $user->account_id]);
sleep(1);
$this->get($this->url() . '?q=' . $invoice->title, $this->userAuthHeader($user))
->seeJson([
'Title' => 'Invoice: ' . $invoice->number . ($invoice->title ? ' - ' . $invoice->title : ''),
'Description' => 'Customer: ' . $invoice->customer->name,
'Type' => 'Invoice',
])
->assertResponseStatus(200);

Related

How to fix Sometimes happen 500 error in Laravel

I have done configurations to fetch data from database and assign corresponding to it.
It works Fine. but sometimes issues happen like undefined index or target class not found.if i refresh again issues not happen that time.
Note: sometimes happens only. so i can't find what exact issue.
AppserviceProvider in boot method i call below function
public function CustomInit(){
if (env('DB_DATABASE') != '') {
// Configuration Setup for Email Settings
if (Schema::hasTable('email_settings')) {
$result = DB::table('email_settings')->get();
$mail_config = array(
"default" => $result[0]->value,
"from" => [
"address" => $result[3]->value,
"name" => $result[4]->value
],
"mailers" => [
"smtp" => [
'transport' => 'smtp',
"host" => $result[1]->value,
"port" => $result[2]->value,
"encryption" => $result[5]->value,
"username" => $result[6]->value,
"password" => $result[7]->value,
'timeout' => null,
],
]
);
Config::set('mail',$mail_config);
$site_settings = SiteSettings::all();
Config::set(
[
'laravel-backup.backup.name' => $site_settings[0]->value,
'laravel-backup.monitorBackups.name' => $site_settings[0]->value,
'laravel-backup.notifications.mail.from' => $result[3]->value,
'laravel-backup.notifications.mail.to' => $result[3]->value,
]
);
}
if (Schema::hasTable('site_settings')) {
$site_settings = DB::table('site_settings')->get()->pluck('value', 'name');
$rand = str_random(6);
if ($site_settings['site_url'] == '' && $_SERVER['HTTP_HOST']) {
$url = "http://" . #$_SERVER['HTTP_HOST'];
$url .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", #$_SERVER['SCRIPT_NAME']);
SiteSettings::where('name', 'site_url')->update(['value' =>$url]);
}
if (!#$_SERVER['HTTP_HOST']) {
Config::set('app.url', $site_settings['site_url']);
URL::forceRootURL($site_settings['site_url']);
}
View::share("site_name", $site_settings['site_name']);
View::share("version", $site_settings['version']);
View::share("version", str_random(4));
View::share('favicon', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
View::share('logo_web_1', url('logos/' . $site_settings['logo_web_1'] . '?v=' . $rand));
View::share('logo_web_2', url('logos/' . $site_settings['logo_web_2'] . '?v=' . $rand));
View::share('email_logo', url('logos/' . $site_settings['email_logo'] . '?v=' . $rand));
View::share('web_favicon', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
define('SITE_NAME', $site_settings['site_name']);
define('LOGO_URL', url('logos/' . $site_settings['logo_web_1'] . '?v=' . $rand));
define('EMAIL_LOGO', url('logos/' . $site_settings['email_logo'] . '?v=' . $rand));
define('FAV_ICON', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
}
if (Schema::hasTable('join_us')) {
$join_us = DB::table('join_us')->get()->pluck('value', 'name');
View::share("app_store", $join_us['app_store']);
View::share("play_store", $join_us['play_store']);
}
if (Schema::hasTable('api_credentials')) {
// For Google Key
$google_map_result = DB::table('api_credentials')->where('site', 'GoogleMap')->get();
define('MAP_KEY', $google_map_result[0]->value);
define('MAP_SERVER_KEY', $google_map_result[1]->value);
View::share('map_key', $google_map_result[0]->value);
// For TWILLO Key
$twillo_result = DB::table('api_credentials')->where('site', 'Twillo')->get();
define('TWILLO_SID', $twillo_result[0]->value);
define('TWILLO_TOKEN', $twillo_result[1]->value);
define('TWILLO_FROM', $twillo_result[2]->value);
// For TWILLO Key
$fcm_result = DB::table('api_credentials')->where('site', 'FCM')->get();
Config::set(
['fcm.http' => [
'server_key' => $fcm_result[0]->value,
'sender_id' => $fcm_result[1]->value,
'server_send_url' => 'https://fcm.googleapis.com/fcm/send',
'server_group_url' => 'https://android.googleapis.com/gcm/notification',
'timeout' => 10,
],
]
);
}
$current_route = url()->current();
if (Route::current()) {
$current_route = Route::current()->uri();
}
View::share('current_route', $current_route);
}
}
Thanks in Advance...
Short answer is don't try and read the .env file in your controller, retrieve the values through a corresponding config file instead.
Long answer - since Laravel 5.2.0 "if you use the config:cache command during deployment you MUST make sure you are only calling the env function from within your configuration files, and not from anywhere else in your application" - https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
In the code you've cited you're calling the .env file direct with :
if (env('DB_DATABASE') != '') {
Depending on which driver you're using, instead you want to retrieve this through the config/database.php file :
if(config('database.mysql.database' != '') {
That will provide a more stable method of retrieving the relevant value so you can see if it is empty or not.

PHP Braintree Gateway API

Be patient with me, I am trying to create a Braintree Gateway for my wordpress booking system with no knowledge of php. i have downloaded the php library files from Braintree and ive implemented the area for api connection and creating a transaction using the following code below. This code was taken and tweaked from another gateway! Is this a good method to use? Would this work?
My Code
$config = new Braintree\Configuration();
$config->environment($api_keys_merchant_id);
$config->merchantId(trim($api_keys_merchant_id));
$config->publicKey(trim($api_keys_public_key));
$config->privateKey(trim($api_keys_private_key));
$gateway = new Braintree\Gateway($config);
// Create transaction
$result = $gateway->transaction()->sale([
'amount' => $price,
'paymentMethodNonce' => 'nonceFromTheClient',
'options' => [ 'submitForSettlement' => true ]]);
if ($result->success) {
print_r("success!: " . $result->transaction->id);
} else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " . $result->transaction->processorResponseCode);
print_r("\n text: " . $result->transaction->processorResponseText);
} else {
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
} ```
Personally, I do not understand what the problem is, so please state it, if any. In terms of adjustments, from the code sample attached, I would say:
don't reference unknown variables or share context about them (eg: $parsedCredentials is initialised but not used; also what is $request?)
use "use" statements at the top of the file instead of using the FQCN; it makes it easier to understand what the dependencies are and what the code does.
$gateway = new Braintree_Gateway([
'environment' => $api_keys_merchant_id,
'merchantId' => trim($api_keys_merchant_id),
'publicKey' => 'use_your_public_key',
'privateKey' => 'use_your_private_key'
]);
$result = $gateway->transaction()->sale([
'amount' => $price,
'paymentMethodNonce' => 'nonceFromTheClient',
'options' => [ 'submitForSettlement' => true ]]);
if ($result->success) {
print_r("success!: " . $result->transaction->id);
} else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " . $result->transaction->processorResponseCode);
print_r("\n text: " . $result->transaction->processorResponseText);
} else {
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}

Laravel 5.5: File download FileNotFoundException?

I'm building a projectmanagement system, where users can upload file attachments to tasks. These attachments are stored in directory 'storage/app/public/projects//'. Uploading works like it should, in the right directory under the right ID.
However when I want to download said attachment, somehow the file can't be found. I've provided the code from my up- and download methods, as well as my 'local' driver configuration.
Driver configuration:
'local' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'storage'
],
Upload method:
$sExt = $request->file('attachment')->getClientOriginalExtension();
$sHashedName = substr(
sha1(str_replace(' ', '', pathinfo($request->file('attachment')->getClientOriginalName(), PATHINFO_FILENAME))
), 0, 14);
if ( ! Storage::disk('local')->exists($sHashedName . '.' . $sExt)) {
$request->file('attachment')->storeAs(
'/projects/'.$oTask->project->id, $sHashedName . '.' . $sExt, 'local'
);
}
$oTask->attachments()->create([
'name' => $request->name,
'location' => $sHashedName . '.' . $sExt,
'user_id' => Auth::id()
]);
Current download method:
public function downloadAttachment(Project $project, Task $task, Attachment $attachment)
{
var_dump(rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location));
if (rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location)) {
return response()->download(rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location));
} else {
return $this->redirectWithAlert(
'error',
'download',
'attachment',
$attachment->name,
'/projects/'.$project->id.'/tasks/'.$task->id
);
}
}
This was my last attempt before posting this question. I have also tried Storage::url('/projects/<project_id>/<filename>') and a number of other things, but none work. I have linked a public storage directory according to the Laravel docs (with php artisan storage:link). I'm probably missing something logical here, but I'm completely lost.
The public_path function refers to ./public/, and not the storage disk 'public' that can be found in ./storage/app/public/
One way of solving this would be to replace public_path('/projects/' with storage_path('app/public/projects/'

Facebook batch request on /me/photos does not schedule my posts

I was using the facebook graph api without batch requests to schedule posts of pictures to my pages.
Now I am trying to work with batch requests but I have an issue, the photo are posted immediately, even if I set the parameters to delay it.
Example:
$args = array(
'message' => $this->message,
);
$args['published'] = false;
$args['scheduled_publish_time'] = strtotime($this->programmed_dt);
$appsecretProof = hash_hmac('sha256', $facebookPage['access_token'], self::APP_SECRET);
$queries[] = array('method' => 'POST',
'relative_url' => urlencode('/' . $facebookPage['id'] . '/photos?access_token=' . $facebookPage['access_token'] . '&appsecret_proof=' . $appsecretProof),
'body' => $args,
'attached_files' => 'file1',
);
$params['file1'] = '#' . realpath('images/' . $timestamp . '.jpg');
$urlPost = '?batch=' . json_encode($queries) . '&access_token=' . self::ACCESS_TOKEN;
$res = $this->fb->api($urlPost, 'POST', $params);
I have a response with the post ID, but the photo post is not scheduled ... Do you see anything wrong?
Thanks.
Found:
published and scheduled_publish_time should be passed to the relative_url
$relativeUrl = '/' . $facebookPage['id'] . '/photos?published=' . (string) $args['published'];
$relativeUrl .= $args['published'] ? '' : '&scheduled_publish_time=' . $args['scheduled_publish_time'] . '&access_token=' . $facebookPage['access_token'] . '&appsecret_proof=' . $appsecretProof;

OpenCart: How to disable province display on the invoice?

Although we have provinces in the Netherlands we do not use them in an address (postcode is the most important thing with us). For this reason I disabled the province in the OpenCart checkout process. It still displays however on the invoice I print out, and since no province is filled in, the first province on the list is standard displayed, which is often the wrong one. For this reason I want to take away the province from the OpenCart invoice.
So I opened admin/view/template/sale/order_invoice.tpl and searched for the relevant part. Unfortunately, the address is referred to as $order['payment_address'] and $order['shipping_address']. Somehow, that code prints out the address including breaklines (<br />).
My question is now: how do I disable just the province in the customer address displayed on the invoice?
Open up also the controller class admin/controller/sale/order.php and check for the relevant parts where the $order['payment_address'] and $order['shipping_address'] are filled and comment out the appropriate lines (where the province is added to the string/array).
The same thing should also be done in the frontend - catalog/controller/account/order.php.
Should be something like this:
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
//'{zone}',
//'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
//'zone' => $order_info['payment_zone'],
//'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
You would probably also have to change the format line from
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
to (see the /* and */ comment):
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' /*. "\n" . '{zone}'*/ . "\n" . '{country}';
To the comment:
Now I am not sure, it is possible that the addresses format is stored within an order after it is created. In that case, change the appropriate lines in controllers to these:
/*if ($order_info['payment_address_format']) { // <-- same for $order_info['shipping_address_format']
$format = $order_info['payment_address_format'];
} else {
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}*/
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' /*. "\n" . '{zone}'*/ . "\n" . '{country}';
For me this solution works:
edit in: admin/controller/sale/order.php
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
//'zone' => $order_info['shipping_zone'],
//'zone_code' => $order_info['shipping_zone_code'],
'zone' => '',
'zone_code' => '',
'country' => $order_info['shipping_country']
First it didn't work, i thought it was a cache problem and clear all the cache, but it did not work. Then I searched on the request order_invoice and this was also used in /system/storage/modification/admin/controller/sale. After clear the modification cache it worked!

Categories