how to access current locale inside model eloquent laravel? - laravel-5

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.

Related

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

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();
}

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]);

Can't filter data from database using getSelect()->where() Magento 2

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!
I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

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();
};

Simplifying CodeIgniter controllers

I have a block of code I'd like to put in my CI 2.x core folder and reuse via a base controller that would be extended by all of my other controllers.
Here is the code that appears in every controller and I want to move to somewhere more central:
$data['navigation'] = generate_navigation(); // helper function
$data['country'] = code2country(); // helper function
$data['langs'] = $this->select_country_model->get_langs();
// Get copy and images for page
$query = $this->common_model->get_content('markets', 'architectural');
// Load title, description and keywords tags with data
foreach ($query as $row) {
$data['title'] = $row->page_title;
$data['description'] = $row->description;
$data['keywords'] = $row->keywords;
}
How do I put this in my base controller (MY_controller.php) and then send the data to my view from the extended controller. Do I still use $data[] = and $this->load->view('whatever', $data)?
Yeah, you can still pass this along in a $data variable, but you'll need to assign it so that you can access it from the other controller like this:
class MY_Controller extends CI_Controller {
var $data = array();
function __construct()
{
$this->load->model('select_country_model');
$this->load->model('common_model');
$this->data['navigation'] = generate_navigation(); // helper function
$this->data['country'] = code2country(); // helper function
$this->data['langs'] = $this->select_country_model->get_langs();
$query = $this->common_model->get_content('markets', 'architectural');
foreach ($query as $row) {
$this->data['title'] = $row->page_title;
$this->data['description'] = $row->description;
$this->data['keywords'] = $row->keywords;
}
}
}
Then just extend you controller with MY_Controller and you will have access to the $data with $this->data.

Resources