can not use pagination() for an array object in laravel - arrays

I am constructing an array in Laravel 5.7. I would like to paginate it, but it errors because of array feature. what shall I do?
In MyController.php:
$result = array();
foreach ($sameDateMatches as $key => $date) {
array_push($result, [
'date' => $key,
'day_of_week' => getDayOfWeek($key),
'matches' => $date,
]);
}
if (!empty($_GET['page'])) {
$result = $result->paginate(10);
$pagination = $result;
} else {
$result = $result;
$pagination = null;
}
return returnSuccessfulResponse(
trans('api.response.successful.show'),
[
'Scheduled Matches' => $result,
],
$pagination
);
Call to a member function paginate() on array

You can only use paginate on an instance of QueryBuilder or on an Eloquent query.
Instead, if you need to 'paginate' an array, you can use PHP array_chunk.
array_chunk($result, 10, true);

I solved my problems using make() and LengthAwarePaginator as below:
if (!empty($_GET['page'])) {
$per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
$page = $_GET['page'];
$result = $result instanceof Collection ? $result : Collection::make($result);
$result = new LengthAwarePaginator(
$result->forPage($page, $per_page)->values(),
$result->count(),
$per_page,
$page,
['path' => request()->url()]
);
$pagination = $result;
} else {
$pagination = null;
}

Related

Cant change single value in session array in Laravel

This my method update for products. And cant to change qty of product. Data saved inside foreach, but nothing change out of this. I can't understand what the problem.
if (!session()->has('products')) {
session()->put('products', []);
}
$products = session()->get('products');
foreach ($products as $item) {
if (isset($item[$product->id])) {
$item[$product->id]['qty'] = 10;
dd($products); // dd($item) - changes
$request->session()->put('products', $products);
return redirect()->back();
}
}
session()->push('products', [
$product->id => [
'product' => $product,
'qty' => 1
]
]);
return redirect()->back();
As you can see there is dd($products) - so its not change. But if dd($item) so it has qty 10.
I can solved this with next:
foreach ($products as $key => $value) {
if (isset($value[$product->id])) {
$value[$product->id]['qty'] = 10;
$products[$key] = $value;
$request->session()->put('products', $products);
return redirect()->back();
}
}
Just add a $key => $value and save it in $products[$key] = $value;

Cakephp 2.8 Why does my search_between function give me a warning?

public function search_between() {
$min = $this->request->query['min'];
$max = $this->request->query['max'];
$conditions = array('Ad.price BETWEEN ? AND ?' => array($min,$max));
$ads = $this->Anuncio->find('all',array('conditions' => $conditions));
$this->set('ads',$ads);
}
Warning: strlen() expects parameter 1 to be string, array given.
**Thank's for your help I'm new to asking questions here.**
try this:
public function search_between() {
$min = $this->request->query['min'];
$max = $this->request->query['max'];
$conditions = array('Anuncio.price >=' => $min,'Anuncio.price <=' $max));
$ads = $this->Anuncio->find('all',array('conditions' => $conditions));
$this->set('ads',$ads);
You can use Cakephp mysql query it will works as like as cakephp query
if(!empty($min) && !empty($max)){
$ads = $this->Anuncio->query('SELECT * from Anuncio WHERE Anuncio.price BETWEEN "'.$min.'" AND "'.$max.'"');
}
else{
$ads = $this->Anuncio->query('SELECT * from Anuncio');
}

how to show as row_number() in codeignitier

need help what wrong with my code where this my sql command where successfull run in mysql :
SELECT func_inc_var_session() As row_number ,
vruasjalan2.*
FROM vruasjalan2 Where skid = #skid
ORDER BY kategoriruasjalanid, subkategoriruasjalanid,ruasjalanid;"
but when i want to display in my controller row_number start error say"Call to undefined method Jalan_model::num_rows()"
public function ajax_list()
{
$list = $this->Jalan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $Jalan) {
$no++;
$row = array();
$row[] = $no;
$row[] = $Jalan->row_number;
$row[] = $Jalan->ruasjalanid;
$row[] = $Jalan->skid;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Jalan->count_all(),
"recordsFiltered" => $this->Jalan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
and this is my model
public function get_list_companys()
{
$this->db->select('vruasjalan2.*');
$this->db->from($this->table);
$this->db->order_by('kategoriruasjalanid','asc');
$query = $this->db->get();
$result = $query->result();
$companys = array();
foreach ($result as $row)
{
$companys[] = $row->kategoriruasjalanid;
}
return $companys;
}
if there any expert know this problems

CodeIgniter Session do not saving Array

i using CodeIgniter Session with database for save a array with $_FILES, but don't save. I do this (but the array never increment):
The post of form, redirects to himself.
Function to upload e load the page of upload.
public function getUpload($codtemp, $codmessage){
$this->load->library('session');
$this->layout = '';
$data = array();
$data['codmessage'] = $codmessage;
$data['codtemp'] = $codtemp;$tempfiles= $this->session->userdata('tempfiles');
if (isset($_FILES['attachment']))
{
$files = $this->fixGlobalFilesArray($_FILES['attachment']);
foreach($files as $file)
{
$tempfiles[$codtemp][] = $file;
}
$this->session->set_userdata('tempfiles', $tempfiles);
unset($files);
}
$this->parser->parse('attachment_upload', $data);
}
private static function fixGlobalFilesArray($files) {
$ret = array();
if(isset($files['tmp_name']))
{
if (is_array($files['tmp_name']))
{
foreach($files['name'] as $idx => $name)
{
$ret[$idx] = array(
'name' => $name,
'tmp_name' => $files['tmp_name'][$idx],
'size' => $files['size'][$idx],
'type' => $files['type'][$idx],
'error' => $files['error'][$idx]
);
}
}
else
{
$ret = $files;
}
}
else
{
foreach ($files as $key => $value)
{
$ret[$key] = self::fixGlobalFilesArray($value);
}
}
return $ret;
}
Before save the array, serialize the data and after get the data, unserialize. If data is empty, create a array

How to only display the search results when needed in cakephp

I have the following situation where I want to only display the search results when user search for something. Currrently, as I access my search page, all the search results is being displayed and if user search for a particular thing, it displays that accordingly. The following is the code in my search controller. I added a pagination for it to paginate.
function simple_search() {
$this->User->recursive = 1;
$this->Passion->recursive = 1;
$this->User->unBindModel(array('hasMany' => array('Topic','Post')),false);
$conditions = array();
$options;
$or_conditions = array();
$final_conditions = array();
$search_fields = array('User.firstName', 'User.lastName', 'User.email', 'User.displayName'); //fields to search 'Video.tags','Video.desc'
$this->layout = "mainLayout";
$value='';
if(!empty($this->params["url"]["value"])){
$value = $this->params["url"]["value"];
}
$searches = explode(" ", $value);
foreach ($search_fields as $f) {
array_push($conditions, array("$f Like" => "$value%"));
for ($i = 0; $i < count($searches); $i++) {
if ($searches[$i] != "") {
array_push($conditions, array("$f Like" => "$searches[$i]%"));
}
}
array_push($or_conditions, array('OR' => $conditions));
$conditions = array();
}
$final_conditions = array('OR' => $or_conditions);
$users = $this->User->find('all', $final_conditions);
$this->paginate = array(
'conditions' => $final_conditions,
'limit' => 10
);
$users = $this->paginate('User');
$this->set('search_fields', $users);
}
remove that find('all'), you overwrite $users right after that.
if(empty($this->params["url"]["value"]))$users = array();
else $users = $this->paginate('User');

Resources