I am attempting to store basket data in a session in Laravel 5 via AJAX but each time I try and push an item to the array stored as the value to 'basket', the existing 'basket' array is overwritten.
Below is my controller method:
public function add(Request $request)
{
$success = false;
if ($request->ajax()) {
$ticket = Ticket::find((int) $request->get('ticket_id'));
if ($ticket) {
if (!$request->session()->has('basket')) {
$request->session()->put('basket', []);
}
$item = [
'attraction.name' => $ticket->attraction->name,
'ticket.quantity' => $request->get('quantity'),
'ticket.price' => $ticket->price,
];
$request->session()->push('basket', [$ticket->id => $item]);
$success = true;
}
}
return response()->json(['success' => $success]);
}
An item is set in the basket session array on the first instance, but I am expecting it to add to this array rather than overwrite when I post more item data over to this method.
The end result I'm looking to achieve is this:
Array
(
[basket] => Array
(
[123] => Array
(
[attraction.name] => Attraction 1
[ticket.quantity] => 2
[ticket.price] => 14.5
)
[456] => Array
(
[attraction.name] => Attraction 2
[ticket.quantity] => 3
[ticket.price] => 12
)
)
)
I've tried using the Session facade equivalent methods, but to no avail :(
Any help would be greatly appreciated. Thanks :)
I had tried array_merge() but again my session was being overwritten. So, after putting my debug hat on yet again, I've found the reason why it was happening.
Session data was not persisting after each request. As my session wasn't being remembered, !$request->session()->has('basket') was always evaluating to true therefore my basket session was being set back to an empty array each time.
I needed to return my request as JSON using the below line in order for my session data to persist. Maybe this is because I have dataType: 'json' as a property in my AJAX call?
return response()->json($request);
I also took your advice and grabbed the basket session array, pushed new data to it and put back into session.
Sorted! Thank you both for your help :)
I experienced a similar issue and discovered that after adding values to the session you need to call
session()->save();
Related
In my symfony controller script, Im passing the quantity of my shopping cart. And im able to get the print_r as the following. The problem Im facing is I tried various ways to access the quantity for no success, can sombody help me on how to access this quantity element
public function detailsAction($id, Request $request)
{
$book = $this->getDoctrine()
->getRepository('AppBundle:Booklist')
->find($id);
print_r($request->request->get('form'));
die($request->request->get('form'));
return $this->render('books/details.html.twig', array('book' => $book, 'quantity' => 1));
}
OUTPUT with print_r
Array ( [quantity] => 1 [Add to Cart] => [_token] => Y8XHbH7lHphAFQ5lIjhQShoIleeSj9iGpen1rhxTBz4 ) Array
can somebody help me on accessing quantity??
You have dumped $request->request->get('form') and there is a quantity in it. It should be easy to get the quantity.
$form = $request->request->get('form');
var_dump($form['quantity']);
So I have this array:
$data = array(
'item_1' => $this->input->post('item_1'),
'item_2' => $this->input->post('item_2'),
'item_3' => $this->input->post('item_3')
);
$this->session->set_userdata( 'items', $data );
And I want to add a new item to that array, so the updated array of userdata will be like this:
$data = array(
'item_1' => $this->input->post('item_1'),
'item_2' => $this->input->post('item_2'),
'item_3' => $this->input->post('item_3'),
'item_4' => $this->input->post('item_4')
);
$this->session->set_userdata( 'items', $data );
How to do that, Thank you
Follow these steps to add data to the current session:
$data = $this->session->userdata('items');
$data['item_4'] = $this->input->post('item_4');
$this->session->set_userdata('items', $data);
Here, we first take out the current session items in an array, add another item to the array, you can do a array_push() but I prefer the above. Now, set the session back with the updated data.
Got this from ellislab:
Adding Custom Session Data
A useful aspect of the session array is that you can add your own data to it and it will be stored in the user's cookie. Why would you want to do this? Here's one example:
Let's say a particular user logs into your site. Once authenticated, you could add their username and email address to the session cookie, making that data globally available to you without having to run a database query when you need it.
To add your data to the session array involves passing an array containing your new data to this function:
$this->session->set_userdata($array);
Where $array is an associative array containing your new data. Here's an example:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
If you want to add userdata one value at a time, set_userdata() also supports this syntax.
$this->session->set_userdata('some_name', 'some_value');
So in essence you should be able to create the item you want to add and then add it to the session by using $this->session->set_userdata("item_4", "item_4"); or $this->session->set_userdata($newdata) if you want to add many items .
i m trying to to get the request values of form in zend framework
earlier i was using the post method
but the the iphone app is sending me data in get method .
how do i can use it has i was using the post values like
$post = array(
'id'=>'2',
'email'=>'4',
)
i want to get values also in this form value when a form is submitted .
i was using this to get post values
$post = $this->getRequest ()->getPost ();
and i tried this to get get method values
$post = $this->getRequest();
but
i get this error
Cannot use object of type Zend_Controller_Request_Http as array in
this is the full error message
"Zend_Controller_Request_Http Object ( [_paramSources:protected] =>
Array ( [0] => _GET [1] => _POST ) [_requestUri:protected] =>
/platinum-picks/p-picks/index/registration [_baseUrl:protected] =>
/platinum-picks/p-picks [_basePath:protected] => [_pathInfo:protected]
=> /index/registration [_params:protected] => Array ( [controller] => index [action] => registration [module] => default )
[_rawBody:protected] => [_aliases:protected] => Array ( )
[_dispatched:protected] => 1 [_module:protected] => default
[_moduleKey:protected] => module [_controller:protected] => index
[_controllerKey:protected] => controller [_action:protected] =>
registration [_actionKey:protected] => action ) Fatal error: Cannot
use object of type Zend_Controller_Request_Http as array in D:\Program
Files\Zend\Apache2\htdocs\platinum-picks\application\models\User.php
on line 267"
If I understand correctly, you want to get the values passed using GET method and you have done the same successfully with POST values. The only change you need to make in such a scenario is this:
$post = $this->getRequest()->getPost ();
becomes
$get = $this->getRequest()->getParams();
This will also return parameters from other sources:
Retrieves a merged array of parameters, with precedence of userland params (see setParam()), $_GET, $_POST (i.e., values in the userland params will take precedence over all others).
So refer to the manual if this may be a problem for you.
You can find the GET variables using for example:
$this->getRequest()->getParams();
Or, for a specific variable:
$this->getRequest()->getParam('myVar');
This will also search for POST values. To search the GET vars only, use:
$this->getRequest()->getQuery('myVar');
My question relates to pulling data from a remote source and saving it to a local database. With the saveAll(), the parent data gets saved correctly, but not the child data.
protected function _saveLocal($_rekeyedData) {
//Set the invoice header and line items models
if (!isset($this->LocalHeader)) {
$this->loadModel('LocalHeader');
$this->LocalHeader->create();
// $this->LocalHeader->set($_rekeyedData);
if (!isset($this->LocalDetail)) {
$this->loadModel('LocalDetail');
$this->LocalDetail->create();
}
}
if ($this->LocalHeader->saveAll($_rekeyedData, array('validate' => 'first'))) {
$this->Session->setFlash('Your data has been saved.');
} else {
$this->Session->setFlash('Data load failed.');
}
debug( $this->LocalDetail->invalidFields() );
}
In this function, I load the models, then attempt to saveAll(). A sample record looks like this:
[1] => Array
(
[LocalHeader] => Array
(
[SOPNUMBE] => CR014076
[DUEDATE] => 2012-04-10 00:00:00
[DOCDATE] => 2012-04-10 00:00:00
[DOCAMNT] => 12000.00000
[SUBTOTAL] => 12000.00000
)
[LocalDetail] => Array
(
[0] => Array
(
[ITEMNMBR] => BASIC SERVICE
[QUANTITY] => 1.00000
[UOFM] => EA
[UNITPRCE] => 12000.00000
[TAXAMNT] => .00000
[CONTSTARTDTE] => 1900-01-01 00:00:00
[CONTENDDTE] => 1900-01-01 00:00:00
[SOPNUMBE] => CR014076
)
)
)
All that gets saved is the LocalHeader record. My hunch is that it has something to do with the array('validate' => 'first'). I think I need to do something separate like validateMany when using saveAll(), but I can't remember where I saw something like that or if I just made it up.
I've read many of the related questions in SO, but none of the offered solutions worked for me.
Any help is appreciated. Please feel free to ask if you have any questions.
EDIT:
This is the header model and this is the detail model.
I think the issue is that neither of those records exists yet. According to the docs
If neither of the associated model records exists in the system yet
(for example, you want to save a new User and their related Profile
records at the same time), you’ll need to first save the primary, or
parent model.
You can read more here with an example.
I am working on PHPunit tests and so far everything is great. There is one issue, however, and it is with the following setup. Ideally I'd like to select the next value in the sequence (postgreSQL) and pass that into the function so I can validate it against the array returned from my class being tested (new row in database).
The issue is that before the array is returned from the data provider (if I echo it) it is the correct value, but during the test it comes through as blank. Is there a particular series of steps I'm missing in here in terms of what I expect or must I do this a different way?
/**
* #dataProvider testSignupProvider
*/
public function testSignup($a, $b, $c)
{
...stuff is done with $a,$b,$c
}
public function testSignupProvider()
{
$uid = fetchOne(X("SELECT currval('users_id_seq')"));
return array(
array(false, array(), $error4),
array(
'email'=>'stack#overflow.com',
'password'=>'youaintgonnagetit',
$error3
),
array(
array('id'=>$uid,'email'=>'PHPUNIT#gmail.com','username'=>'Guest'),
array('email'=>'PHPUNIT#gmail.com','password'=>'youaintgonnagetit'),
null
)
);
}
Output:
Array
(
- [id] =>
+ [id] => 2
[email] => PHPUNIT#gmail.com
[username] => Guest
)
I've gotten around this by assigning the 'id' array element to '#id' and in the function test I pull the current id in the sequence at that time.
Still will accept an answer to anyone who can tell me why this behavior occurs but hopefully this will help anyone else with this issue.