2015-11-10 59 views
1

我的控制器看起來像這樣如何在Laravel5用雄辯的數據庫中插入多行

<?php 

    namespace App\Http\Controllers; 

    use Illuminate\Http\Request; 
    use Illuminate\Support\Facades\Auth; 
    use App\Http\Requests; 
    use App\Http\Controllers\Controller; 
    use App\Http\Middleware\Role; 
    use Illuminate\Support\Facades\Input; 
    use App\Http\Requests\PaymentRequest; 
    use App\User; 
    use App\Invoice; 
    use App\comments; 
    use Session; 
    use Validator; 


    class CollectionController extends Controller 
    { 
     /** 
     * Display a listing of the resource. 
     * 
     * @return Response 
     */ 

     public function __construct(){ 

     $this->middleware('role:collector'); // replace 'collector' with whatever role you need. 
    } 


    public function postPayment(PaymentRequest $request){ 

      $insertPayment=Input::get(); 

      $payment= new paymentrecieved(); 
      $comment= new comments(); 

      $payment->invoice_id=$insertPayment['invoiceid']; 
      $payment->recieved_amount=$insertPayment['recieved_amount']; 
      $payment->refno=$insertPayment['ref_no']; 
      $payment->date=$insertPayment['date']; 

     if($insertPayment['adjustmentmode']=='Option') 
      $payment->adjust_mode='NONE'; 
      else 
      $payment->adjust_mode=$insertPayment['adjustmentmode']; 
      $payment->save(); 

      $request->session()->flash('alert-success', 'Payment Has Been inserted Successfully'); 
      return redirect('collection/payment/1'); 

      //dd($insertPayment); 
} 




     } 

所以在我的形式支付相關的細節是在一個數組我想知道我怎麼可以創建多行?並將它們一起保存一次。

感謝&問候

回答

4

試試這個,

$result = Banner::create([ 
      'name' => $name, 
      'status' => $status, 
      'description' => $description, 
      'category_id' => $category_id, 
      'ordering' => $ordering, 
      'link' => $link, 
     ]); 
$result = Banner::create($data); 

你可以傳遞多維數組在這種情況下,你必須使用insert

for(..){ 
$data[] = [ 
       'name' => $name, 
       'status' => $status, 
       'description' => $description, 
       'category_id' => $category_id, 
       'ordering' => $ordering, 
       'link' => $link, 
      ]; 
} 

$result = Banner::insert($data) 

注:這不會更新/創建時間戳,所以你必須通過插入數組。

希望它可以幫助..

+0

我試圖理解你的想法:P – Vikram

+0

它扔'MassAssignmentException在Model.php行424:'例外,我需要這些變量fillabel分配的請求類 – Vikram

+0

是的,如果您使用create方法並希望能夠分配這些字段,則它們需要可填寫。另外,爲了插入多維數組,您需要使用'insert'方法,而不是'create'方法。 –