User57
User57

Reputation: 2505

How to put session value store into database?

I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]

Upvotes: 0

Views: 103

Answers (5)

Mohamed Mo Kawsara
Mohamed Mo Kawsara

Reputation: 4688

it depends on how did you store it into session, so if you used push, then it will be stored as array.

anyways change your code to the following:

$orders =  $request->session()-> pull('order',$defaultOrdersArrayCanBeHere);
$order = new Order();
$order->school_id = $orders['school_id'];
$order->order_date = $orders['order_date'];
$order->time_slot = $orders['time_slot'];

UPDATE:

Did you push it to session as so: session()->push('order', $order);

where:

$order = [
'school_id'=> $schoolId;
'order_date'=> $orderDate;
'time_slot'=> $timeSlot;
]

Upvotes: 0

Ritesh Khatri
Ritesh Khatri

Reputation: 1301

try like this,

$orders =  $request->session()->get('order');
print_r($orders);

if you getting orders of school id array then you can get it by $orders['school_id']; and if you getting std object then you can retrieve it by $orders->school_id; Use as per output of print_r(orders) Then you can store it by

If std object ::

$order = new Order();
$order->school_id = $orders[0]->school_id;
$order->order_date = $orders[0]->order_date;
$order->time_slot = $orders[0]->time_slot;
$order->save();

If array ::

$order = new Order();
$order->school_id = $orders[0]['school_id'];
$order->order_date = $orders[0]['order_date'];
$order->time_slot = $orders[0]['time_slot'];
$order->save();

Upvotes: 1

plmrlnsnts
plmrlnsnts

Reputation: 1684

Call to a member function pluck() on array

Your $orders variable is an array so you can't use pluck. You can do $order['key'] to access their values. Or as others suggested, use the helper function array_get

Upvotes: 0

NeuTronas
NeuTronas

Reputation: 273

Session holds all data in Array and not Collection. Function pluck() can only be used for the collection.

Try doing array_get($orders, 'school_id'); as already mentioned by Marc or just $request->session()->get('order')['school_id'];

Upvotes: 0

user6705732
user6705732

Reputation:

I would use the array_get helper.

https://laravel.com/docs/5.5/helpers#method-array-get

array_get($orders, 'school_id');

Additionally you can use a fallback as third parameter in case the value is not present in the session.

Upvotes: 0

Related Questions