vendredi 27 janvier 2017

Trying to get property of non-object from another controller Laravel 5.3

I don't think this is a typical non-object error, but hopefully someone with more knowledge than me can figure it out.

I have the following Controller:

class MangopayController extends Controller {

/**
 * @var \MangoPay\MangoPayApi
 */
private $mangopay;

public function __construct(MangoPayApi $mangopay)
{
    $this->mangopay = $mangopay;
}

/**
 *  Add a user to mangopay. This should be done for every new user
 *
 * @return True if successful
 */

public function addUserToMangopay($user_id)
{
    // get the admin user object
    $user = User::where('id', $user_id)->first();
    // set fields for mangopay
    $newMangopayUser = new UserNatural();
    $newMangopayUser->Tag = $user->role;
    $newMangopayUser->FirstName = $user->first_name;
    $newMangopayUser->LastName = $user->last_name;
    $newMangopayUser->Birthday = $user->birthday;
    $newMangopayUser->Nationality = $user->nationality;
    $newMangopayUser->CountryOfResidence = $user->country_of_residence;
    $newMangopayUser->Email = $user->email;
    // add user to mango pay, should return user object if successful
    $result = $this->mangopay->Users->Create($newMangopayUser); // <-- this line is causing issues
    if (is_object($result)) {
        $user->mangopay_id = $result->Id;
        $user->save();
        return true;
    } 
}

The above works fine if I run it using a route like this:

Route::get('/add-user-to-mangopay/{user_id}', [ 'as' => 'user_id', 'uses' => 'MangopayController@addUserToMangopay']);

But, if I try and run this from my RegisterController which looks like this:

class RegisterController extends MangopayController

/**
 * Handle a registration request for the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    $result = $this->addUserToMangopay($user->id);

    if ($this->addUserToMangopay($user->id)) {
        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    } else {
        return $this->registered($request, $user)?: redirect($this->redirectPath()->with('alert-danger', 'There was a problem creating your account'));
    }

}

Then I get the error "Trying to get property of non-object" from the MangopayController line:

    $result = $this->mangopay->Users->Create($newMangopayUser);

I have tried various iterations of the code but can't get it to work.

Anyone able to help? Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire