Laravel 5.1 – Данные формы хранения ошибок,

У меня проблема с данными хранения из формы запроса. После оплаты paypal. Это моя ошибка

SQLSTATE [23000]: нарушение ограничений целостности: 1048 Столбец «fullname_ship» не может быть нулевым (SQL: вставить в orders ( subtotal , shipping , fullname_ship , updated_at , created_at ) значения (10, 1,, 2016-05-09 15:39: 40, 2016-05-09 15:39:40))

МОДЕЛЬ ORDER.PHP

 <?php namespace dixard; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $table = 'orders'; protected $fillable = [ 'subtotal', 'shipping', 'fullname_ship', ]; } 

CHECKOUT PAGE – ЗАКАЗ – ДЕТАЛИ.PHP

 <form class="login" method="post" action="{{url('payment')}}"> {{csrf_field()}} <div class="checkout-wrapper"> <div class="container"> <div class="text-alert"> <p>Returning customer? <a href="#">Click here to login</a></p> </div><!-- /.text-alert --> <div class="row"> <div class="col-md-6"> <h2>Fatturazione</h2> <fieldset id="billinfo"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="fullname_ship">Nome e cognome<sup>*</sup></label> <input type="text" class="form-control dark" id="fullname_ship" placeholder="Nome" name="fullname_ship" > </div><!-- /.form-group --> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="address_shipping">Indirizzo <sup>*</sup></label> <input type="text" class="form-control dark" id="address_shipping" placeholder="Via/Piazza/Viale" > </div><!-- /.form-group --> </div> <div class="col-md-6"> <div class="form-group"> <label for="address2_shipping">Interno/Scala <sup>*</sup></label> <input type="text" class="form-control dark" id="address2_shipping" placeholder="ScalaA/Interno:11" > </div><!-- /.form-group --> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="province_shipping">Provincia<sup>*</sup></label> <input type="text" class="form-control dark" id="province_shipping" placeholder="Roma,Milano,ecc" > </div><!-- /.form-group --> </div> <div class="col-md-6"> <div class="form-group"> <label for="country_shipping">Paese<sup>*</sup></label> <input type="text" class="form-control dark" id="country_shipping" placeholder="Paese" value="" > </div><!-- /.form-group --> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="email_shipping">Email<sup>*</sup></label> <input type="text" class="form-control dark" id="email_shipping" placeholder="Email" value="{{Auth::user()->email}}" > </div><!-- /.form-group --> </div> <div class="col-md-6"> <div class="form-group"> <label for="phone_shipping">Cellulare<sup>*</sup></label> <input type="text" class="form-control dark" id="phone_ship" placeholder="Telefono/Cellulare" name="phone_ship" > </div><!-- /.form-group --> </div> </div> </fieldset> <form> 

PAYPALCONTROLLER.PHP

 <?php namespace dixard\Http\Controllers; use Illuminate\Http\Request; use dixard\Http\Requests; use dixard\Http\Controllers\Controller; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use PayPal\Rest\ApiContext; use PayPal\Auth\OAuthTokenCredential; use PayPal\Api\Amount; use PayPal\Api\Details; use PayPal\Api\Item; use PayPal\Api\ItemList; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\ExecutePayment; use PayPal\Api\PaymentExecution; use PayPal\Api\Transaction; use dixard\Order; use dixard\OrderItem; class PaypalController extends BaseController { private $_api_context; public function __construct() { // setup PayPal api context $paypal_conf = \Config::get('paypal'); $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret'])); $this->_api_context->setConfig($paypal_conf['settings']); } // postPayment public function postPayment(Request $request) { $payer = new Payer(); $payer->setPaymentMethod('paypal'); $items = array(); $subtotal = 0; $cart = \Session::get('cart'); //ottenere tutta l'informazione dalla session cart $currency = 'EUR'; // impostiamo tutte le informazioni foreach($cart as $producto){ $item = new Item(); $item->setName($producto->name) ->setCurrency($currency) ->setDescription($producto->extract) ->setQuantity($producto->quantity) ->setPrice($producto->price); $items[] = $item; $subtotal += $producto->quantity * $producto->price; } $item_list = new ItemList(); $item_list->setItems($items); $details = new Details(); $details->setSubtotal($subtotal) ->setShipping(1); $total = $subtotal + 1; $amount = new Amount(); $amount->setCurrency($currency) ->setTotal($total) ->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($item_list) ->setDescription('Pedido de prueba en mi Laravel App Store'); // Redirect se si completa il pagamento O si cancella $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(\URL::route('payment.status')) ->setCancelUrl(\URL::route('payment.status')); $payment = new Payment(); $payment->setIntent('Sale') ->setPayer($payer) ->setRedirectUrls($redirect_urls) ->setTransactions(array($transaction)); try { $payment->create($this->_api_context); } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); exit; } else { die('Ups! Algo salió mal'); } } foreach($payment->getLinks() as $link) { if($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // add payment ID to session, \Session::put('paypal_payment_id', $payment->getId()); if(isset($redirect_url)) { // redirect to paypal return \Redirect::away($redirect_url); } // se ci sono errori return \Redirect::route('cart-show') ->with('message', 'Ups! Error .'); } public function getPaymentStatus(Request $request) { // Get the payment ID before session clear $payment_id = \Session::get('paypal_payment_id'); // clear the session payment ID \Session::forget('paypal_payment_id'); $payerId = \Input::get('PayerID'); $token = \Input::get('token'); if (empty($payerId) || empty($token)) { return \Redirect('products') ->with('message', 'Hubo un problema al intentar pagar con Paypal'); } $payment = Payment::get($payment_id, $this->_api_context); $execution = new PaymentExecution(); $execution->setPayerId(\Input::get('PayerID')); $result = $payment->execute($execution, $this->_api_context); if ($result->getState() == 'approved') { //$this->saveOrder(); $this->saveOrder($request); \Session::forget('cart'); return \Redirect('orderComplete') ->with('message', 'Compra realizada de forma correcta'); } return \Redirect('orderComplete') ->with('message-error', 'La compra fue cancelada'); } protected function saveOrder(Request $request) { $subtotal = 0; $cart = \Session::get('cart'); $shipping = 1; foreach($cart as $producto){ $subtotal += $producto->quantity * $producto->price; } //$cellulare =$request->get('fullname_ship'); $order = Order::create([ 'subtotal' => $subtotal, 'shipping' => $shipping, 'fullname_ship' => $request->get('fullname_ship'), //'user_id' => \Auth::user()->id ]); foreach($cart as $producto){ $this->saveOrderItem($producto, $order->id); } } protected function saveOrderItem($producto, $order_id) { OrderItem::create([ 'price' => $producto->price, 'quantity' => $producto->quantity, 'product_id' => $producto->id, 'order_id' => $order_id ]); } } выплачивается <?php namespace dixard\Http\Controllers; use Illuminate\Http\Request; use dixard\Http\Requests; use dixard\Http\Controllers\Controller; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use PayPal\Rest\ApiContext; use PayPal\Auth\OAuthTokenCredential; use PayPal\Api\Amount; use PayPal\Api\Details; use PayPal\Api\Item; use PayPal\Api\ItemList; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\ExecutePayment; use PayPal\Api\PaymentExecution; use PayPal\Api\Transaction; use dixard\Order; use dixard\OrderItem; class PaypalController extends BaseController { private $_api_context; public function __construct() { // setup PayPal api context $paypal_conf = \Config::get('paypal'); $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret'])); $this->_api_context->setConfig($paypal_conf['settings']); } // postPayment public function postPayment(Request $request) { $payer = new Payer(); $payer->setPaymentMethod('paypal'); $items = array(); $subtotal = 0; $cart = \Session::get('cart'); //ottenere tutta l'informazione dalla session cart $currency = 'EUR'; // impostiamo tutte le informazioni foreach($cart as $producto){ $item = new Item(); $item->setName($producto->name) ->setCurrency($currency) ->setDescription($producto->extract) ->setQuantity($producto->quantity) ->setPrice($producto->price); $items[] = $item; $subtotal += $producto->quantity * $producto->price; } $item_list = new ItemList(); $item_list->setItems($items); $details = new Details(); $details->setSubtotal($subtotal) ->setShipping(1); $total = $subtotal + 1; $amount = new Amount(); $amount->setCurrency($currency) ->setTotal($total) ->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($item_list) ->setDescription('Pedido de prueba en mi Laravel App Store'); // Redirect se si completa il pagamento O si cancella $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(\URL::route('payment.status')) ->setCancelUrl(\URL::route('payment.status')); $payment = new Payment(); $payment->setIntent('Sale') ->setPayer($payer) ->setRedirectUrls($redirect_urls) ->setTransactions(array($transaction)); try { $payment->create($this->_api_context); } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); exit; } else { die('Ups! Algo salió mal'); } } foreach($payment->getLinks() as $link) { if($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // add payment ID to session, \Session::put('paypal_payment_id', $payment->getId()); if(isset($redirect_url)) { // redirect to paypal return \Redirect::away($redirect_url); } // se ci sono errori return \Redirect::route('cart-show') ->with('message', 'Ups! Error .'); } public function getPaymentStatus(Request $request) { // Get the payment ID before session clear $payment_id = \Session::get('paypal_payment_id'); // clear the session payment ID \Session::forget('paypal_payment_id'); $payerId = \Input::get('PayerID'); $token = \Input::get('token'); if (empty($payerId) || empty($token)) { return \Redirect('products') ->with('message', 'Hubo un problema al intentar pagar con Paypal'); } $payment = Payment::get($payment_id, $this->_api_context); $execution = new PaymentExecution(); $execution->setPayerId(\Input::get('PayerID')); $result = $payment->execute($execution, $this->_api_context); if ($result->getState() == 'approved') { //$this->saveOrder(); $this->saveOrder($request); \Session::forget('cart'); return \Redirect('orderComplete') ->with('message', 'Compra realizada de forma correcta'); } return \Redirect('orderComplete') ->with('message-error', 'La compra fue cancelada'); } protected function saveOrder(Request $request) { $subtotal = 0; $cart = \Session::get('cart'); $shipping = 1; foreach($cart as $producto){ $subtotal += $producto->quantity * $producto->price; } //$cellulare =$request->get('fullname_ship'); $order = Order::create([ 'subtotal' => $subtotal, 'shipping' => $shipping, 'fullname_ship' => $request->get('fullname_ship'), //'user_id' => \Auth::user()->id ]); foreach($cart as $producto){ $this->saveOrderItem($producto, $order->id); } } protected function saveOrderItem($producto, $order_id) { OrderItem::create([ 'price' => $producto->price, 'quantity' => $producto->quantity, 'product_id' => $producto->id, 'order_id' => $order_id ]); } } 

routes.php

 Route::post('payment', array( 'as' => 'payment', 'uses' => 'PaypalController@postPayment', )); Route::get('payment', array( 'as' => 'payment', 'uses' => 'PaypalController@getPayment', )); Route::get('payment/status', array( 'as' => 'payment.status', 'uses' => 'PaypalController@getPaymentStatus', )); 

Кажется, что вы получаете пустое fullname_ship здесь:

 fullname_ship' => $request->get('fullname_ship'), 

Итак, вы должны проверить ввод и указать пользователю заполнить это поле (с required ). Или вы можете установить для него значение по умолчанию (если оно пустое, будет использоваться значение dafault). Или вы можете пометить это поле как nullable в БД, и оно пустое, вы не получите ошибку.

Самый простой способ – добавить элемент формы:

 <input required="required" type="text" class="form-control dark" id="fullname_ship" placeholder="Nome" name="fullname_ship" > 

$request->get('fullname_ship') не будет работать с Laravel 5.

От Laravel 5.0 до текущего значения 5.2 правильные способы ввода формы:

 $request->input('fullname_ship') or Input::get('fullname_ship') 

Второй способ будет работать, только если вы use Input; в верхней части контроллера.

Обратитесь к этому, если вам нужно что-нибудь еще.

Тот же объект Request не будет передан всем вашим функциям в контроллере.

Вы должны прочитать значение fullname_ship внутри postPayment() функции postPayment() .

Кроме того, вы можете передать все данные из $request другим своим функциям

 public function postPayment(Request $request) { ... $input = $request->all(); ... $this->getPaymentStatus($input); ... } public function getPaymentStatus ($input) { ... $fullname_ship = $input['fullname_ship']; ... } 

Я исправляю проблему, я добавил все входы значений в сеансовую тележку, поэтому метод saveOrder я получаю все входы из сеанса и хранения в моей базе данных. После сохранения заказа я удалил сеансовую тележку. Спасибо за всех ребят!