How to optimaze looping , get data from another API with lumen - laravel

when i use guzzle to get data member on join to data content is so heavy, can samebody tell me how to fix it?
$getNewest=$this->Get(env('TestUrl').'listcast');
if (!empty($getNewest['DATA'])) {
foreach ($getNewest['DATA'] as $data)
{
$client = New CLient();
$reqGet = $client->get(env('MemberUrl').'user-token-member/'.$data['member_id']);
$resGet = json_decode($reqGet->getBody(),true);
$array['id']=$data['id'];
$array['title']=$data['title'];
$array['member_name'] =$resGet['DATA']['FIRSTNAME']." ".$resGet['DATA']['LASTNAME'];
$array['avatar'] = $resGet['DATA']['MEMBER_IMAGE'];
$array['desc'] = $data['desc'];
$newest[] = $array;
}
} else {
$newest = array();
}

I don't know exactly what is the reason for its low speed, but there are some modifications that you should apply on your code.
Don't use env() in your code. Instead define a config file for example connection.php in config folder and set your configs in it, because config file will be cached in your production server by laravel. You can cache config by running php artisan config:cache
For example config/connection.php
<?php
return [
'test_url'=>env('TestUrl'),
'member_url'=>env('MemberUrl'),
];
It is not required to make a new object of Client class in every iteration of foreach. You put it outside of the loop.
$getNewest=$this->Get(config('connection.test_url').'listcast');
if (!empty($getNewest['DATA'])) {
$client = New CLient();
foreach ($getNewest['DATA'] as $data){
$reqGet = $client->get(config('connection.member_url').'user-token-member/'.$data['member_id']);
$resGet = json_decode($reqGet->getBody(),true);
$array['id']=$data['id'];
$array['title']=$data['title'];
$array['member_name'] =$resGet['DATA']['FIRSTNAME']." ".$resGet['DATA']['LASTNAME'];
$array['avatar'] = $resGet['DATA']['MEMBER_IMAGE'];
$array['desc'] = $data['desc'];
$newest[] = $array;
}
} else {
$newest = array();
}

Related

Running same query in 2 different views: What's the proper way?

Just getting started into laravel and need to run the same db query for 2 different views, I know I could just create 2 controllers and perform the same query in both passing it to each view.
But, is that the proper way? Or is there a way without repeating my code?
Thanks!
Edit:
I have the following function inside a controller:
protected function getLocation($url)
{
$match = ['url' => $url];
$location = DB::table('location')->where($match)->first();
if (!$location) {
abort(404);
}
return $location;
}
the controller is returning that data to a view:
public function showsubcatandlocation($service)
{
$category = $this->getCat($service);
$location = $this->getLocation($category);
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
}
What's the proper way to reuse the getLocation function? Or should I just copy it in the new controller? I just need to use it in those 2 views.
maybe scope Query helps?
class Location extends Model
{
public function scopeMatch($query, $url)
{
return $query->where('url', $url);
}
}
And then your two controllel methods will be
$location = Task::match($url)->first();
if (!$location) {
abort(404);
}
return $location;
$category = $this->getCat($service);
$location = Task::match($category['url'])->first();
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);

how to access current locale inside model eloquent laravel?

I have been searching alot for this problem solution. I need to access current app locale set earlier inside my controller function using \App::setLocale('en'). But later on i was unable to get current locale inside model using app()->getLocale() or App::isLocale('en') or App::getLocale().
Please Look at below code inside orders model:
public function getOrderDetailAttribute($value)
{
$new = [];
$arr = json_decode($value,true);
if(!empty($arr))
foreach($arr as $val)
{
$temp["id"] = $val["id"];
if(App::isLocale('en'))
$temp['itemName'] = $val["name"];
else
$temp['itemName'] = $val["name_ar"];
if(!empty($val["size"]))
$temp['size'] = $val["size"];
$temp['Qty'] = $val["quantity"];
$temp['price'] = $val["price"];
$temp['image'] = $val["p_img_url"];
$new[] = $temp;
unset($temp);
}
return $new;
}
Please suggest.
Thanks.

Laravel Eloquent ORM save: update vs create

I've got a table and I'm trying to use the save() method to update/create lines. The problem is that it always create new lines. The following code gives me about 12 lines each time I run it. They don't have a unique id before inserting them but the combination of name and DateTimeCode is unique. Is there's a way to use those two in order for laravel to recognize them as exist()? Should I consider using if exist with create and update instead?
foreach ($x as $y) {
$model = new Model;
$model->name = ''.$name[$x];
$model->DateTimeCode = ''.$DateTimeCode[$x];
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
I assume this would work in laravel 4.x:
foreach ($x as $y) {
$model = Model::firstOrCreate(array('name' => name[$x], 'DateTimeCode' => DateTimeCode[$x]));
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
I think that in this case you will need to search for it before updating or creating:
foreach ($x as $y) {
$model = Model::where('name', name[$x])->where('DateTimeCode', DateTimeCode[$x])->first();
if( ! $model)
{
$model = new Model;
$model->name = ''.name[$x];
$model->DateTimeCode = ''.DateTimeCode[$x];
}
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};

CodeIgniter CLI returns blank when utilizing a model. How to run cron securely?

I am trying to run a cron from the command line utilizing CodeIgniter.
Initially it was returning a blank but utilizing the Codeigniter forum I found there was a bug in version 2.1.3 which required a line edit in Input.php
That was fixed. Still it wasn't working, it was just loading my homepage.
More searching led me to change my uri_protocol to AUTO in my config, and finally the CLI was working with the example outlined on the CI website.
However when I have utilized a model in the cron controller, once again the CLI returns blank bangs head
The controller
<?php
class Cron extends CI_Controller
{
public function admin_update()
{
$this->load->model('admin_model');
$this->admin_model->admin_cron();
}
}
The model function
function admin_cron()
{
$this->load->database();
echo "two";
}
It seems to be the $this->load->database() line that is breaking it.. as in if i remove this it outputs 'two'..
Does anyone have any idea why?
Thanks
You are not providing any input for $this->load->database();
Instead it should be something like this
var $DB; //global variable
$this->DB = $this->load->database('database1',TRUE);
use $this->DB for running the db operations now like,
$this->DB->query($query);
Put these config enteries in the config/database.php
$db['database1']['hostname'] = 'serverIP';
$db['database1']['username'] = 'username';
$db['database1']['password'] = 'pwrd';
$db['database1']['database'] = 'DB name';
$db['database1']['dbdriver'] = 'mysql';
$db['database1']['dbprefix'] = '';
$db['database1']['pconnect'] = FALSE;
$db['database1']['db_debug'] = TRUE;
$db['database1']['cache_on'] = FALSE;
$db['database1']['cachedir'] = '';
$db['database1']['char_set'] = 'utf8';
$db['database1']['dbcollat'] = 'utf8_general_ci';
$db['database1']['swap_pre'] = '';
$db['database1']['autoinit'] = TRUE;
$db['database1']['stricton'] = FALSE;
PS: http://ellislab.com/codeigniter/user-guide/general/models.html#conn
above link is on how to connect to a database

CakePHP 1.3 running shell with cron - passing data to email template

I'm running a shell script via a cron job. It correctly sends an email. However I want to be able to pass data to the email template from the database which I seem unable to do.
Here is the shell
App::import('Core', 'Controller');
App::import('Component', 'Email');
class ExampleShell extends Shell {
var $uses = array('User');
function main() {
$users = $this->User->find('all');
$this->Controller =& new Controller();
$this->Email =& new EmailComponent(null);
$this->Email->initialize($this->Controller);
$this->Email->reset();
$this->Email->to = 'xx<xx#xx.com>';
$this->Email->subject = "Subject";
$this->Email->template = 'example';
$this->Email->sendAs = "both";
$this->Controller->set('users', $users);
$this->Email->send();
}
}
The variable $users does not seem to be available in the example.ctp file? How can I pass data from the shell script to the template please?
I managed to do it in following way
class ExampleShell extends Shell {
var $uses = array('User');
var $Controller = null;
function __construct(&$dispatch) {
App::import('Core', 'Controller');
App::import('Controller', 'App');
$this->Controller = & new Controller();
App::import('Component', 'Email');
$this->Email = new EmailComponent();
$this->Email->initialize($this->Controller);
parent::__construct($dispatch);
}
function main() {
$users = $this->User->find('all');
$this->Controller =& new Controller();
$this->Email =& new EmailComponent(null);
$this->Email->initialize($this->Controller);
$this->Email->reset();
$this->Email->to = 'xx<xx#xx.com>';
$this->Email->subject = "Subject";
$this->Email->sendAs = "both";
$this->Controller->set('users', $users);
$this->Email->send(null, 'template_1');
}
}
I hope it helps someone.
Make sure template is located where it should be app/views/elements/email/html/template_1.ctp and app/views/elements/email/text/template_1.ctp for text version. You should create layouts too in app/views/layouts/email/html/default.ctp and app/views/layouts/email/text/default.ctp

Resources