将多个值添加到会话中以插入到数据透视表中


Adding multiple values into Session to insert in a pivot table

我有三个表delivery-request_item、items和一个透视表delivery-request_item。在我的create.blade.php中,我有一个按钮,它将添加其中一个项目,该项目的相应数量由用户选择。

我的解决方案是将项目和数量提交给会议。现在我的问题是,我只能创建一个记录,如果我决定添加另一个项,上一个项将被覆盖。

createblade.php

{{Form::open(array('method'=>'POST','url'=>'delivery-requests'))}}
{{Form::text('requested_by', Auth::user()->email)}}
<div>
    {{Form::label('Shows Items from table')}}   
    {{Form::select('item_id', $items)}}
    {{Form::label('Quantity')}}
    {{Form::text('item_quantity')}}
    {{Form::submit('add item',array('name'=>'addItem'))}}
    {{Form::submit('remove item', array('name' => 'removeItem'))}}
</div>
<hr>
<div>
    <table>
        <theader>
            <tr>
               <td>ITEM NAME</td>
               <td>QUANTITY</td>
            </tr>
        </theader>
            <!-- loop through all added items and display here -->
        @if(Session::has('item_id'))
        <h1>{{ Session::get('item_id') }}</h1>
        @endif
        @if(Session::has('item_quantity'))
        <h1>{{ Session::get('item_quantity')}}</h1>
        @endif
    </table>
</div>
{{Form::submit('submit', array('name' => 'submit'))}}
{{Form::close()}}

DeliveryRequestsController@Store

if(Input::has('addItem'))
{
  Session::flash('item_id', Input::get('item_id'));
  Session::flash('item_quantity', Input::get('item_quantity'));
  $data =  Session::all();
  $item = Item::lists('item_name','id');
  return View::make('test')->with('data',$data)->with('items',$item);   
}

两件事。

  1. 您需要使会话成为一个数组,否则您将始终覆盖。

  2. 您不需要使用flash(),因为一旦发出另一个请求,这些数据就会被删除,这就是闪存数据,这些数据会一直持续到下一个请求。

试试这个:

if(Input::has('addItem')) {
    if(Session::has('items')) {
        Session::push('items', [
            'id'    => Input::get('item_id'),
            'qty'   => Input::get('item_quantity')
        ]);
    } else {
        Session::put('items', [
            'id'    => Input::get('item_id'),
            'qty'   => Input::get('item_quantity')
        ]);
    }
}

Session::push()使用存储在会话中的数组,如果不存在Session::put(),则显然会使用它。

记住,这些数据将是持久的,并且需要在某些情况下清除,就像你完成它一样

有关会话的更多信息,请阅读以下内容:http://laravel.com/docs/session