lundi 9 mai 2016

Laravel 5 - Error storage form data,

i have problem on storage data from request form After payment paypal. This is my error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fullname_ship' cannot be null (SQL: insert into orders (subtotal, shipping, fullname_ship, updated_at, created_at) values (10, 1, , 2016-05-09 15:39:40, 2016-05-09 15:39:40))

MODEL 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- ORDER-DETAIL.PHP

<form class="login" method="post" action="">

 

    <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="" >
                          </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
        ]);
    }
}

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',
));



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire