Reverse product list in Laravel - arrays

How can I reverse the product list in Laravel?
Below is the code:
public function index() {
$products = Product::with('owner', 'memberInfo')->paginate($this->perPage);
return View::make('layouts.sales', array('products' => $products, 'status' => 'all'));
}

You can use Eloquent's reverse() function for collections.
public function index() {
$products = Product::with('owner', 'memberInfo');
$products = $products->reverse()->paginate($this->perPage);
return View::make('layouts.sales', array('products' => $products, 'status' => 'all'));
}

Related

Symfony 5.2 add to session array

I want to add product to my session array but always it overwriting existing product and is only one.
/**
* #Route("/{id}", name="add", methods={"GET"})
*/
public function add(Product $product, Request $request): Response
{
$session= $request->getSession();
$session->set('products', array(
'list' => $product,
));
$this->addFlash('success', 'add');
return $this->render('index.html.twig', [
'product' => $product
]);
}
any suggestion?
You overwrite the session variable each time instead of adding a new product. Try to get the product, add new product, then set the session:
public function add(Product $product, Request $request): Response
{
$session= $request->getSession();
$products = $session->get('products', []);
$session->set('products', array(
'list' => array_merge($products['list'] ?? [], [$product])
));
$this->addFlash('success', 'add');
return $this->render('index.html.twig', [
'product' => $product
]);
}
If you want to have distinct products you may use product['id'] as the key
public function add(Product $product, Request $request): Response
{
$session= $request->getSession();
$products = $session->get('products', []);
$products[$product['id']] = $product;
$session->set('products', products);
$this->addFlash('success', 'add');
return $this->render('index.html.twig', [
'product' => $product
]);
}

I am trying to paginate the search results and display it on the template's view file using CakePHP 3.x

This is the controller file where the all the search results are coming from the foreach loop , I tried paginating it, but can't figure out how to do it.
<?php
class SerController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Paginator');
}
public function index()
{
$check_string=$this->request->data('check');
$check_break=explode(" ",$check_string);
$s1=TableRegistry::get('ser_tab');
foreach($check_break as $check)
{
$s11=$s1->find('all')->where(['OR' =>['text LIKE' => '%'.$check.'%','name LIKE' => '%'.$check.'%']]);
$this->set(array('data' => $s11));
}
$this->render('index');
}
}
Your query will take too long execution time. You can do it simply.
Update your index() function like as below
Example [When data from URL]
public function index($data='Default text here'){ /*When get Data from the URL*/
$data = explode(' ', $data);
$conditions = array(); /*All OR conditions will store here*/
foreach ($data as $key => $value) {
$conditions['or'][] = array('text LIKE' => "%$value%");
$conditions['or'][] = array('name LIKE' => "%$value%");
}
$this->paginate = [
'limit' => 25, #Set the limit of post
'conditions'=>[
$conditions /*OR conditions array*/
]
];
$data = $this->paginate();
var_dump($conditions,$data); /*Debug OR Condition array and Query data*/
$this->set(compact('data')); /*Set the Posts to a variable*/
}
Example [When data from POST]
public function index(){
if ($this->request->is('post')) {
$data = $this->request->data('check');
# YOUR CODE HERE
}
}
CakePHP 3.x pagination documentation is HERE

CakePHP Unit Testing with edit methods

I wrote the test testEdit().
public function testEdit() {
$result = $this->_testAction('/articles/edit/1', array('return' => 'vars', 'method' => 'get'));
debug($result);
}
why debug($result) show the null array?
Use var_dump instead of debug
public function testEdit() {
$result = $this->testAction('/articles/edit/1', array('return' => 'vars', 'method' => 'get'));
var_dump($result);
}

Cakephp Custom Find Type Pagination

I created a custom find type, and am trying to paginate the results, but the paginator seems to be ignoring the findType setting. Can someone tell me what I'm doing wrong?
(CakePHP 2.X)
In my Controller:
public function list($username=null) {
$this->Paginator->settings = array(
'Question' => array(
'findType' => 'unanswered',
'conditions' => array('Question.private' => 0),
);
$data = $this->Paginator->paginate('Question');
$this->set('data', $data);
);
Custom find type setup in my Model:
public $findMethods = array('unanswered' => true);
protected function _findUnanswered($state, $query, $results = array()) {
if ($state == 'before') {
$query['order'] = array('Question.created DESC');
$query['conditions'] = array_merge($query['conditions'], array('Question.date_answered' => ''));
return $query;
$this->log($query);
} elseif ($state == 'after') {
return $results;
}
}
Edit
I can paginate the query if I remove $this->Paginate->settings, and replace it with this:
$this->paginate = array('unanswered');
However, I want to add some additional conditions., this doesn't work:
$this->paginate = array('unanswered' => 'conditions' => array('Question.user_id' => $id, 'limit' => 4)) );
Is this possible?
findType was added to the paginator component in CakePHP 2.3, I was on 2.0
http://api.cakephp.org/2.3/class-PaginatorComponent.html

Unit testing the Auth Component

I am using the following code to test the login action in UsersController
public function testLogin() {
$data = array('User' => array(
'username' => 'hello',
'password' => '411'
)
);
$this->Users = $this->generate('Users',array('components'=> array('Auth','Session')));
$this->Users->Auth->staticExpects($this->once())
->method('user')
->with('id');
$this->testAction('/users/login', array('data' => $data, 'method' => 'post'));
}
and the fixture is-
class UserFixture extends CakeTestFixture {
public $import = array('model' => 'User', 'records' => true, 'connection' => 'fixture');
}
adn action is-
public function login() {
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
return false;
$this->Session->setFlash(__('Wrong Username Or Password,Please Try Again'));
}
}
}
It always showing
Expectation failed for method name is equal to when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
What is the problem?Cant find any solution,and the reason also.Please help.
I think your problem mocking the auth component is that in addition to including auth in your components array, you need to specify which methods of Auth to mock, and how to mock them.
The way I deal with AuthComponent in my tests is I create a superclass with a method: _generateMockWithAuthUserId which mocks the Auth component, among other things, the way I need.
I've pasted the code from my superclass below.
class AppControllerTest extends ControllerTestCase {
public function setUp() {
parent::setUp();
$this->User = ClassRegistry::init('User');
}
public function tearDown() {
unset($this->User);
parent::tearDown();
}
public function testPlaceholder(){
// This just here so we don't get "Failed - no tests found in class AppControllerTest"
$this->assertTrue(true);
}
protected function _generateMockWithAuthUserId($contollerName, $UserId){
$this->authUserId = $UserId;
$this->authUser = $this->User->findById($this->authUserId);
$this->controller = $this->generate($contollerName, array(
'methods' => array(
'_tryRememberMeLogin',
'_checkSignUpProgress'
),
'components' => array(
'Auth' => array(
'user',
'loggedIn',
),
'Security' => array(
'_validateCsrf',
),
'Session',
)
));
$this->controller->Auth
->expects($this->any())
->method('loggedIn')
->will($this->returnValue(true));
$this->controller->Auth
->staticExpects($this->any())
->method('user')
->will($this->returnCallback(array($this, 'authUserCallback')));
}
public function authUserCallback($param){
if(empty($param)){
return $this->authUser['User'];
} else {
return $this->authUser['User'][$param];
}
}
}
And then here's a example of a class that inherits from that superclass. Take note of where/how it calls _generateMockWithAuthUserId. Basically, doing that sets up a suitable controller with Auth mocked for the appropriate user id.
<?php
require_once dirname(__FILE__) . DS . 'AppControllerTest.php';
class EmployeeNotesControllerTestCase extends AppControllerTest {
public $fixtures = array(
// your fixtures go here
);
public function setUp() {
parent::setUp();
$this->EmployeeNote = ClassRegistry::init('EmployeeNote');
}
public function tearDown() {
unset($this->EmployeeNote);
parent::tearDown();
}
public function testSupervisorIndexCanNotSeeNotesOnSelf() {
$authUserId = 1;
$this->_generateMockWithAuthUserId('EmployeeNotes', $authUserId);
$this->controller->Session
->expects($this->once())
->method('setFlash');
$result = $this->testAction('supervisor/employee_notes/index/'.$authUserId, array('return' => 'vars', 'method' => 'get'));
$this->assertTrue(empty($result['employeeNotes']));
}
}
Hope that helps.
I have found a solution.it worked.
public function testLogin() {
$data = array('User' => array(
'username' => 'sasa',
'password' => '111'
)
);
$this->Users = $this->generate('Users', array());
$result = $this->testAction('/users/login', array('data' => $data, 'method' => 'post'));
$this->assertEquals($data['User']['username'],$this->Users->Session->read('Auth.User.username'));
$result = $this->testAction('/users/logout');
}

Resources