Only one page of product got with rest admin api - laravel

I have so many pages of products on my development store.But when I try to use products.json to get all of my products, it only take 50 listings(one page).Could anybody solve my doubt?
<?php
$url = 'https://myshopifystore/admin/api/2019-07/products.json';
$result = file_get_contents($url);
$data = json_decode($result, true);
dd($data);
my result like this picture:

The limit property on the request has a default of 50 up to 250. In case you want more use a loop to search though every page until the end.
GET /admin/api/2019-07/products.json?limit=250?page=1
Use
GET /admin/api/2019-07/products/count.json
to get the total product you want to search.
More info about paginated page here
EDIT 1 : The paginated ?page= is now deprecated. It will be remove in version 2020-07. You should use cursor-based pagination.

Below function can help to fetch resources with cursor based pagination in new shopify API
public function request($method,$url,$param = []){
$client = new \GuzzleHttp\Client();
$url = 'https://'.$this->username.':'.$this->password.'#'.$this->domain.'/admin/api/2019-10/'.$url;
$parameters = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
];
if(!empty($param)){ $parameters['json'] = $param;}
$response = $client->request($method, $url,$parameters);
$responseHeaders = $response->getHeaders();
$tokenType = 'next';
if(array_key_exists('Link',$responseHeaders)){
$link = $responseHeaders['Link'][0];
$tokenType = strpos($link,'rel="next') !== false ? "next" : "previous";
$tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
$tobeReplaceWith = ["","","",""];
parse_str(parse_url(str_replace($tobeReplace,$tobeReplaceWith,$link),PHP_URL_QUERY),$op);
$pageToken = trim($op['page_info']);
}
$rateLimit = explode('/', $responseHeaders["X-Shopify-Shop-Api-Call-Limit"][0]);
$usedLimitPercentage = (100*$rateLimit[0])/$rateLimit[1];
if($usedLimitPercentage > 95){sleep(5);}
$responseBody = json_decode($response->getBody(),true);
$r['resource'] = (is_array($responseBody) && count($responseBody) > 0) ? array_shift($responseBody) : $responseBody;
$r[$tokenType]['page_token'] = isset($pageToken) ? $pageToken : null;
return $r;
}
using above function in controller
$ids = [];
$nextPageToken = null;
do{
$response = $shop->request('get','products.json?limit=250&page_info='.$nextPageToken.'&rel=next');
foreach($response['resource'] as $product){
array_push($ids, $product['id']);
}
$nextPageToken = $response['next']['page_token'] ?? null;
}while($nextPageToken != null);

Related

Requesting SOAP using CURL on Codieigniter 4

I am consuming a service using CURL. I am able to connect all the functions of the services in the form of a CXF Service List using the following code.
$client = \Config\Services::curlrequest();
$response = $client->request('GET', 'www.soapservice.co.za/service');
var_dump($response->getBody());
Var Dump Returns a string with Available services
The service has 10 functions listed in this manner getDataFunction.
How do I invoke the function? Or how do I get the contents of the body and start using Service functions?
Any help would be appreciated
This is how I resolved my issue using Codeignter 4 and Soap Client.
public function ownersearch()
{
helper(['form']);
$username = "";
$password = "";
$url = 'getProperty?wsdl';
$first_name = $this->request->getVar('first_name');
$second_name = $this->request->getVar('second_name');
$last_name = $this->request->getVar('last_name');
$user_id = $this->request->getVar('user_id');
$session_id = session()->get('user_id');
$client = new \SoapClient($url);
$deedsusagemodel = new UsageLogModel();
$args = [
'idNumber'=> $user_id,
'username'=> $username,
'password' => $password,
'officeCode' => 1
];
$usageData = [
'user_id' => $session_id
];
if($user_id != Null){
$response = $client->getFunctionByIDNumber($args);
$ndata = $response->return;
if($ndata->errorResponse->errorCode == 64)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
if($ndata->errorResponse->errorCode == 550)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
else{
$usagemodel->insert($usageData);
return $this->respond($ndata, 200);
}
}
}

joomla - router change url when getting the name of product

I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)

Laravel sort by join value many to many relationship with pagination

Lets say that each user has domains and I would like to be able to display those domains in a tabular format.
As a user I should be able to sort by the domain attributes.
The domain attributes include sortable entities such as page rank.
In laravel I grab a collection of domains that are related to the currently logged in user like so:
$users = User::with(array('domains' => function($query)
{
// $query->where('name','like','%all%'); //subquery filter
}))->whereId(Session::get('user')['id'])->first();
if(isset($sort))
{
//What goes here?
}
I can itterate through the results like so:
$domains = $users->domains;
$collection = Paginator::make($domains->toArray(), $page, $pagesize);
To get the result set I would do this:
$collection->getItems();
How do I apply a filter to the domain results to apply sorting by a particular value?
So I got done typing this message and decided to try something:
public function listView()
{
$order = Input::get('order') === 'asc' ? 'asc' : 'desc'; // default desc
$page = Input::get('page') ? Input::get('page') : 1; // default 1
$model = new Domain;
$pagesize = Input::get('pagesize');
if(isset($pagesize))
{
if($pagesize == 'all')
{
$pagesize = count($model::all());
}elseif(!is_numeric($pagesize))
{
$pagesize = DomainsController::$default_pagesize;
}
}else{
$pagesize = DomainsController::$default_pagesize;
}
$users = User::with(array('domains' => function($query)
{
$sort = Input::get('sort') ? Input::get('sort') : NULL; // default NULL
$order = Input::get('order') ? Input::get('order') : 'DESC'; // default DESC
if(isset($sort))
{
$query->orderBy($sort, $order);
}
}))->whereId(Session::get('user')['id'])->first();
$queries = DB::getQueryLog();
$last_query = end($queries);
$domains = $users->domains;
$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
$collection = Paginator::make($domains->toArray(), $page, $pagesize);
$data = array(
'totalCount' => count($domains),
'pageSize' => $collection->getPerPage(),
'numberOfPages' => $collection->getLastPage(),
'currentPage' => $collection->getCurrentPage(),
'startNumber' => $collection->getFrom(),
'endNumber' => $collection->getTo(),
'results' => $collection->getItems(),
'sortstr'=>((Input::get('pagesize')) == '' ? '' : '&pagesize='.(Input::get('pagesize'))).'&order='.($order == 'asc' || null ? 'desc' : 'asc'),
'querystr'=>(Input::get('pagesize')) == '' ? '' : '&pagesize='.(Input::get('pagesize')).'&order='.(Input::get('order') == '' ? 'desc' : (Input::get('order')))
);
$this->layout->content = View::make('pages.domains.list',$data);
}
This is working code.
To answer my own question, the problem I was having is simply that the $sort value was inaccessible from the function SEE function($query).

codeigniter pagination pulling item more then once

This is a very irritating issue. I have my codeigniter pagination set up and so I thought working, but looking at it closer it seems that on the last page it's pulling in previous results to fill the page in.
So say I want ten per page and have fourteen results. The first page has ten results, and so does the second. When it should be the first has ten and the second has four. It would be fine if it was just repeating one result, but it's irritating to have to scroll through six previous results. Any help would be much appreciated.
in my controller I have the pagination code
$config = array();
$config["base_url"] = base_url()."myStories/".$id;
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config['num_links'] = 2;
$choice = $config["total_rows"] / $config["per_page"];
//$config["num_links"] = round($choice);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
and then in my model I have the count and then the actual results coming back
public function my_count() {
//This counts all the stories that belong to that author
$author = $this->uri->segment(2);
$this->db->where('author', $author);
$this->db->where(array('approved !=' => 'd'));
$query = $this->db->get('story_tbl');
return $query->num_rows();
}
public function pullMyStories($limit, $start){
//This pulls back all the stories that belong to that author
$this->db->limit($limit, $start);
$this->db->order_by("date", "desc");
$author = $this->uri->segment(2);
$this->db->where(array('approved !=' => 'd'));
$this->db->where('author', $author);
$story = $this->db->get('story_tbl');
return $story->result();
}
the route I have set up that does work
$route['myStories/(:any)'] = "story/viewStories/$1";
I thought initially that my count was count was wrong, but even with a count of 14, 20 results come back.
For further information I am more than positive that my baseUrl is correct. I have modified my .htaccess to get rid of the index.php and have edited my route file to make the controller disappear from the url. To try and make it easy to remember for the user.
I am also very sure that the uri segments are correct. If they were not correct then my page would not be coming up at all.
I have tried all the normal solutions and nothing has worked. That is why I am asking here and why I have placed a bounty on this question.
var $base_url = ''; // The page we are linking to
var $prefix = ''; // A custom prefix added to the path.
var $suffix = ''; // A custom suffix added to the path.
var $total_rows = 0; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $use_page_numbers = FALSE; // Use page number for segment instead of offset
var $first_link = 'First';
var $next_link = '->';
var $prev_link = '<-';
var $last_link = 'Last';
var $uri_segment = 2;
var $full_tag_open = '';
var $full_tag_close = '';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $first_url = ''; // Alternative URL for the First Page.
var $cur_tag_open = ' <strong>';
var $cur_tag_close = '</strong>';
var $next_tag_open = ' ';
var $next_tag_close = ' ';
var $prev_tag_open = ' ';
var $prev_tag_close = '';
var $num_tag_open = ' ';
var $num_tag_close = '';
var $page_query_string = FALSE;
var $query_string_segment = 'per_page';
var $display_pages = TRUE;
var $anchor_class = '';
Your problem is that you are passing the wrong parameters to your pullMyStories method. On the first page you will be apply the following limit to your query
LIMIT 0,10
Then on the second page
LIMIT 1,10
Then on the third
LIMIT 2,10
So you pagination is only moving forward one item at a time instead of ten. So you need to change this
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
To this
'query' => $this->data_model->pullMyStories($config['per_page'], ($page * $config['per_page'])),
I recently tried so hard to about ci pagination.
I think, your codes right.
What exactly uri string on second page?.. And this listing function is index() ?
Try if it works for you:
$config = array();
$config["base_url"] = base_url()."myStories/"; #change in base url
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config['num_links'] = 2;
#$choice = $config["total_rows"] / $config["per_page"];
//$config["num_links"] = round($choice);
$this->pagination->initialize($config);
#$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; #no need of calculation here
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($this->uri->segment(3)), #change here send the offset directly
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
function pullMyStories($offset = 0){
$story = $this->db->where('author', $this->uri->segment(2))->where('approved != d')->order_by("date", "desc")->get('story_tbl', 10, $offset);
return $story->result();
}
Try this. You just need to change the base_url in the correct way. Also be careful and check if you are getting a right number for uri_segment. If not, you can change the number, and get the correct.
// $config = array();
// MUST CHNGE IT I just tell the with simple example. If you have index.php, c name and method name.
$config["base_url"] = base_url()."index.php/controller_name/function_name/";
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3; // BE CARFULL with uri_segment. You need to print it, and be shre that you are getting the right number
$config['num_links'] = 2;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
I update my code, I comment and $config = array();
I did it today in my computer this, and it works. I know that you maybe checked it hundred times, but Check in details it again.
UPDATE with my example:
function index() {
$data['page_title'] = "Items";
$config['base_url'] = base_url() .'index.php/items/index/';
$config['total_rows'] = $this->items_model->count_items(); // Count items from DB
$config['per_page'] = 10;
$config['uri_segment'] = 3;
// Customize
$config['next_link'] = FALSE;
$config['prev_link'] = FALSE;
$config['first_link'] = 'first';
$config['last_link'] = 'last';
$config['cur_tag_open'] = '<a class="current">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['items'] = $this->items_model->get_items($config["per_page"], $page);
$this->load->view('invoice-items', $data);
}
In your controller:
$page = $this->uri->segment(3,0);
Then:
public function pullMyStories($limit, $start){
$author = $this->uri->segment(2);
$this->db
->select('*')
->where('approved !=', 'd')
->where('author', $author)
->order_by('date', 'DESC')
->limit($limit, $start);
$story = $this->db->get('story_tbl');
return $story->result();
Also where do you load the library using the line below?
$this->load->library('pagination');
I'm just gonna throw this in and hope it helps in some way, because I've tested and it works for me. I've made the following assumptions for testing:
id (as in "myStories/".$id in the controller) is taken from $this->uri->segment(2)
story_tbl fields I created were id, author, date
My test files were as follows:
Controller MyStories.php:
public function index()
{
//loading library, model, and assumptions
$this->load->library('pagination');
$this->load->model('m_page', 'data_model');
$id = $this->uri->segment(2);
//
//
//Your code from here...
//
//
$config = array();
$config["base_url"] = $this->config->site_url("myStories/".$id);
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 3;
$config["uri_segment"] = 3;
$config["num_links"] = round($config["total_rows"] / $config["per_page"]);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data = array();
$data['query'] = $this->data_model->pullMyStories($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$data['config'] = $config;
//$data['user'] = $this->users_model->getUser($this->user->user_id);
$this->load->view('userStory_view', $data);
}
BTW, you really want to be using the site_url and not base_url when defining the pagination base_url.
I also commented out the 'user' data in the controller simply because you never gave any info on that.
My test view, userStory_view.php:
<?php echo $links;?>
<!-- -->
<hr>
total rows: <?php echo $config['total_rows'];?>
<hr>
<?php echo $this->db->last_query();?>
<hr>
<!-- -->
<?php foreach ($query as $row):?>
<?php echo $row->author.'<hr>';?>
<?php endforeach;?>
I made no changes to your Model, so no need to show that here.
I added the following line to routes.php:
$route['myStories/(:any)'] = "myStories";
As I said, everything worked for me. Besides my formatting, the only changes I really made were the use of site_url() instead of base_url(), and the commenting of the user data. So pretty stuck as to why you're having issues I'm afraid.
As far as it seems your overall pagination functionality seems to correct. what i want check would the sql query returned in each function and parameters passed to those function coz $author variable has to global and try
$this->db->last_query();
on your both functions my_count() and pullMyStories($limit, $start) and check those function returning right results.
U might also can try writing direct sql query with changing parameters like.
$sql = "SELECT * FROM some_table WHERE author = ? LIMIT ?, ?";
$this->db->query($sql, array($author, $start, $limit));
As i am seeing this would be mostly of query might have been wrong .
Hope this helps.

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources