Laravel "Создание объекта по умолчанию из пустого значения" пока - PullRequest
0 голосов
/ 30 ноября 2018

Все настроено хорошо, нет ошибки опечатки, и я не думаю, что у меня неправильное соединение между MVC, но я получаю ошибку

"Создание объекта по умолчанию из пустого значения"

В течение 3 дней пытаюсь решить эту проблему и не могу найти ее точную причину.

Просмотр файла:

@extends('layouts.app')

@section('header')
  <h1>@lang('messages.paypalsettings')</h1>
  <hr />
  <div style="clear:both">&nbsp;</div>
@endsection
@section('content')
<form action="{{route('admin.paypal.save')}}" method="POST">
  {{ csrf_field() }}
  <div class="col-sm-12">
      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="merchant_email">@lang('messages.merchant_email')</label>
            <input type="text" class="form-control" id="merchant_email" name="merchant_email" value="{{$paypal->merchant_email}}">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="sandbox">@lang('messages.sandbox')</label>
            <select id="sandbox" name="sandbox" class="form-control">
                <option value="1">Yes</option>
                <option value="{{$paypal->sandbox}}">No</option>
            </select>
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">  
            <label for="api_username">@lang('messages.api_username')</label>
            <input type="text" class="form-control" id="api_username" name="api_username" value="{{$paypal->api_username}}">
        </div>
      </div>  
  </div>

  <div style="clear:both">&nbsp;</div>

   <div class="col-sm-12">
      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="api_password">@lang('messages.api_password')</label>
            <input type="text" class="form-control" id="api_password" name="api_password" value="{{$paypal->api_password}}">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">
            <label for="api_secret">@lang('messages.api_secret')</label>
            <input type="text" class="form-control" id="api_secret" name="api_secret" value="{{$paypal->api_secret}}">
        </div>
      </div>

      <div class="col-sm-4 float-left">
        <div class"class="form-group">  
            <label for="currency_code">@lang('messages.currency_code')</label>
            <input type="text" class="form-control" id="currency_code" name="currency_code" value="{{$paypal->currency_code}}">
        </div>
      </div>  
  </div>

  <div style="clear:both">&nbsp;</div>

  <div class="form-group float-right">
    <button type="submit" class="btn btn-primary">@lang('messages.save')</button>
  </div>


</form>
@endsection

Сторона контроллера

namespace AppExample\Http\Controllers;

use Illuminate\Http\Request;
use AppExample\models\Paypal;
use AppExample\models\PaypalSettings;
use AppExample\User;
use App\Invoice;
use App\Item;
use Auth;
use Lang;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Srmklive\PayPal\Services\ExpressCheckout;
use AppExample\IPNStatus;

class PayPalController extends Controller
{
    /**
     * @var ExpressCheckout
     */
    protected $provider;

    public function __construct()
    {
        $this->middleware('auth');
        //$this->provider = new ExpressCheckout();
    }

    public function paypalsettings(){
       $paypalsettings = PaypalSettings::find(1);
        if(!$paypalsettings){
          $paypalsettings = new PaypalSettings;
          $paypalsettings->sandbox = '';
          $paypalsettings->merchant_email = '';
          $paypalsettings->api_username = '';
          $paypalsettings->api_password = '';
          $paypalsettings->api_secret = '';
          $paypalsettings->currency_code = '';
        }
        return view('paypal.index')->with('paypal', $paypalsettings);
    }

public function save_paypalsettings(Request $request){
    $merchant_email = $request->merchant_email;
    $sandbox = $request->sandbox;
    $api_username = $request->api_username;
    $api_password = $request->api_password;
    $api_secret = $request->api_secret;
    $currency_code = $request->currency_code;
    $paypalsettings = PaypalSettings::find(1);

// Здесь начинается ошибка

$ paypalsettings-> merchant_email = $ request-> merchant_email;

    $paypalsettings->sandbox = $sandbox;
    $paypalsettings->api_username = $api_username;
    $paypalsettings->api_password = $api_password;
    $paypalsettings->api_secret = $api_secret;
    $paypalsettings->currency_code = $currency_code;
    $paypalsettings->save();

    // $paypalitems = Paypal::find(1);
    // $paypalitems->item_number = $item_number;
    // $paypalitems->item_name = $item_name;
    // $paypalitems->amount = $amount;
    // $paypalitems->save();        
    return back();
}

    public function paypal_items(){
       $paypal = Paypal::find(1);
        if(!$paypal){
          $paypal = new Paypal;
          $paypal->item_number = '';
          $paypal->item_name = '';
          $paypal->amount = '';
        }
        return view('paypal.index')->with('paypal', $paypal);
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getExpressCheckout(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $cart = $this->getCheckoutData($recurring);

        try {
            $response = $this->provider->setExpressCheckout($cart, $recurring);

            return redirect($response['paypal_link']);
        } catch (\Exception $e) {
            $invoice = $this->createInvoice($cart, 'Invalid');

            session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
        }
    }

    /**
     * Process payment on PayPal.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getExpressCheckoutSuccess(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $token = $request->get('token');
        $PayerID = $request->get('PayerID');

        $cart = $this->getCheckoutData($recurring);

        // Verify Express Checkout Token
        $response = $this->provider->getExpressCheckoutDetails($token);

        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            if ($recurring === true) {
                $response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
                if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
                    $status = 'Processed';
                } else {
                    $status = 'Invalid';
                }
            } else {
                // Perform transaction on PayPal
                $payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
                $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
            }

            $invoice = $this->createInvoice($cart, $status);

            if ($invoice->paid) {
                session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
            } else {
                session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
            }

            return redirect('/');
        }
    }

    /**
     * Parse PayPal IPN.
     *
     * @param \Illuminate\Http\Request $request
     */
    public function notify(Request $request)
    {
        if (!($this->provider instanceof ExpressCheckout)) {
            $this->provider = new ExpressCheckout();
        }

        $post = [
            'cmd' => '_notify-validate'
        ];
        $data = $request->all();
        foreach ($data as $key => $value) {
            $post[$key] = $value;
        }

        $response = (string) $this->provider->verifyIPN($post);

        $ipn = new IPNStatus();
        $ipn->payload = json_encode($post);
        $ipn->status = $response;
        $ipn->save();            
    }

    /**
     * Set cart data for processing payment on PayPal.
     *
     * @param bool $recurring
     *
     * @return array
     */
    protected function getCheckoutData($recurring = false)
    {
        $data = [];

        $order_id = Invoice::all()->count() + 1;

        if ($recurring === true) {
            $data['items'] = [
                [
                    'name'  => 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id,
                    'price' => 0,
                    'qty'   => 1,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success?mode=recurring');
            $data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
        } else {
            $data['items'] = [
                [
                    'name'  => 'Product 1',
                    'price' => 9.99,
                    'qty'   => 1,
                ],
                [
                    'name'  => 'Product 2',
                    'price' => 4.99,
                    'qty'   => 2,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success');
        }

        $data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
        $data['invoice_description'] = "Order #$order_id Invoice";
        $data['cancel_url'] = url('/');

        $total = 0;
        foreach ($data['items'] as $item) {
            $total += $item['price'] * $item['qty'];
        }

        $data['total'] = $total;

        return $data;
    }

    /**
     * Create invoice.
     *
     * @param array  $cart
     * @param string $status
     *
     * @return \App\Invoice
     */
    protected function createInvoice($cart, $status)
    {
        $invoice = new Invoice();
        $invoice->title = $cart['invoice_description'];
        $invoice->price = $cart['total'];
        if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
            $invoice->paid = 1;
        } else {
            $invoice->paid = 0;
        }
        $invoice->save();

        collect($cart['items'])->each(function ($product) use ($invoice) {
            $item = new Item();
            $item->invoice_id = $invoice->id;
            $item->item_name = $product['name'];
            $item->item_price = $product['price'];
            $item->item_qty = $product['qty'];

            $item->save();
        });

        return $invoice;
    }
}

Сторона модели

namespace AppExample\models;

use Illuminate\Database\Eloquent\Model;

class PaypalSettings extends Model
{
  protected $table = 'paypal_settings';

    protected $fillable = [
      'sandbox', 'merchant_email', 'api_username', 'api_password', 'api_secret', 'currency_code'
    ];

    public function paypal(){
      return $this->belongsTo('AppExample\models\Paypal');
    }

    public function subscription(){
      return $this->belongsTo('AppExample\models\Subscription');
    }

}

Маршрутная сторона

Route::get('admin/paypal/edit', 'PaypalController@paypalsettings')->name('admin.paypal.edit');
Route::post('admin/paypal/save', 'PaypalController@save_paypalsettings')->name('admin.paypal.save');

Может быть, я перестала хорошо видеть вещи, стоит подумать о том, чтобы пойти к врачу.Но я ошибаюсь, почему я получаю эту ошибку, в то время как все хорошо, я думаю.Любая помощь высоко ценится, спасибо в продвинутом!

РЕДАКТИРОВАТЬ: полное сообщение об ошибке

"ErrorException (E_WARNING) Создание объекта по умолчанию из пустого значения"

Ошибка начинается с первой строки $paypalsettings->merchant_email = $request->merchant_email;

2ND Редактировать: Var Dump

var_dump ($ paypalsettings);строка 35 под $ paypalsettings = new PaypalSettings;

object(AppExample\models\PaypalSettings)#793 (26) { ["table":protected]=> string(15) "paypal_settings" ["fillable":protected]=> array(6) { [0]=> string(7) "sandbox" [1]=> string(14) "merchant_email" [2]=> string(12) "api_username" [3]=> string(12) "api_password" [4]=> string(10) "api_secret" [5]=> string(13) "currency_code" } ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(false) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(0) { } ["original":protected]=> array(0) { } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } }

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018
public function save_paypalsettings(Request $request){
    $merchant_email = $request->merchant_email;
    $sandbox = $request->sandbox;
    $api_username = $request->api_username;
    $api_password = $request->api_password;
    $api_secret = $request->api_secret;
    $currency_code = $request->currency_code;
    $paypalsettings = PaypalSettings::find(1);

    // The error starts here
    $paypalsettings->merchant_email = $request->merchant_email;

    $paypalsettings->sandbox = $sandbox;
    $paypalsettings->api_username = $api_username;
    $paypalsettings->api_password = $api_password;
    $paypalsettings->api_secret = $api_secret;
    $paypalsettings->currency_code = $currency_code;
    $paypalsettings->save();

    return back();
}

Эта строка $paypalsettings = PaypalSettings::find(1); возвращает null, поскольку модель (id: 1) еще не существует

В следующей строке вы делаете $paypalsettings->merchant_email = $request->merchant_email;

Нопоскольку $paypalsettings является нулем, то, что вы действительно делаете, это null->merchant_email = 'test@test.com';

Я не совсем знаю, чего вы пытаетесь достичь.Но модель должна существовать и тестироваться или создаваться в данный момент.

Могу ли я порекомендовать вам посмотреть, как работает CRUD?https://appdividend.com/2018/02/23/laravel-5-6-crud-tutorial/

0 голосов
/ 30 ноября 2018

Замените вашу функцию paypalsettings следующей функцией:

public function paypalsettings(){
       $paypalsettings = PaypalSettings::find(1);
        if(is_null($paypalsettings)){ //change over here
          $paypalsettings = new PaypalSettings;
          $paypalsettings->sandbox = '';
          $paypalsettings->merchant_email = '';
          $paypalsettings->api_username = '';
          $paypalsettings->api_password = '';
          $paypalsettings->api_secret = '';
          $paypalsettings->currency_code = '';
        }
        return view('paypal.index')->with('paypal', $paypalsettings);
    }
...