php - plantillas - Laravel 5.1-Datos de forma de almacenamiento de error,
laravel foreach index (4)
Tengo un problema en los datos de almacenamiento del formulario de solicitud Después del pago de PayPal. Este es mi error
SQLSTATE [23000]: violación de la restricción de integridad: 1048 La columna ''fullname_ship'' no puede ser nula (SQL: insertar en las
orders
(subtotal
,shipping
,fullname_ship
,updated_at
,created_at
) values (10, 1created_at
2016-05-09 15:39: 40, 2016-05-09 15:39:40)
MODELO DE PEDIDO.PHP
<?php
namespace dixard;
use Illuminate/Database/Eloquent/Model;
class Order extends Model
{
protected $table = ''orders'';
protected $fillable = [
''subtotal'',
''shipping'',
''fullname_ship'',
];
}
PÁGINA DE PAGO-PEDIDO-DETALLE.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
]);
}
}
RUTAS.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'',
));
Soluciono el problema, agregué todas las entradas de valores en el carrito de la sesión, así que en el método saveOrder obtengo todas las entradas de la sesión y el almacenamiento en mi base de datos. Después de guardar orden borré el carro de la sesión. ¡Gracias por todos los chicos!
Parece que estás obteniendo fullname_ship
vacío aquí:
fullname_ship'' => $request->get(''fullname_ship''),
Por lo tanto, debe validar la entrada y decirle a un usuario que complete este campo (con required
). O puede establecer un valor predeterminado (si está vacío, se usará el valor predeterminado). O puede marcar este campo como nullable
en DB y está vacío, no obtendrá un error.
La forma más sencilla es agregar elementos required
al elemento de formulario:
<input required="required" type="text" class="form-control dark" id="fullname_ship" placeholder="Nome" name="fullname_ship" >
$request->get(''fullname_ship'')
no funcionará con Laravel 5.
Desde Laravel 5.0, hasta el valor actual de 5.2, las formas correctas de obtener un formulario de entrada son:
$request->input(''fullname_ship'') or Input::get(''fullname_ship'')
La segunda forma solo funcionará si use Input;
en la parte superior del controlador.
Consulte esto si necesita algo más.
El mismo objeto de Request
no se pasará a todas sus funciones en un controlador.
Debe leer el valor de fullname_ship
dentro de la función postPayment()
.
De lo contrario, puede pasar todos los datos desde $request
a sus otras funciones
public function postPayment(Request $request)
{
...
$input = $request->all();
...
$this->getPaymentStatus($input);
...
}
public function getPaymentStatus ($input)
{
...
$fullname_ship = $input[''fullname_ship''];
...
}