简体   繁体   中英

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"
  ]
]

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();

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.

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'];

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;
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM