user1012181
user1012181

Reputation: 8726

Laravel Model create function returns column with null value

In Laravel, When I run the following query, it returns a row with null values.

//Cards.php

public function __construct(array $attributes = []) {
    $this->gateway = StripeGateway;
} 


protected $fillable = ['user_id', 'card_id', 'customer_id', 'exp_year', 'exp_month', 'funding', 'brand', 'last4'];

public function createNewCardFromCustomer($user_id, $customer)
    {

        $result = $this->create([
            'user_id' => $user_id,
            'customer_id' => $customer->id,
            'card_id' => $customer['sources']['data'][0]->id,
            'exp_year' => $customer['sources']['data'][0]->exp_year,
            'exp_month' => $customer['sources']['data'][0]->exp_month,
            'funding' => $customer['sources']['data'][0]->funding,
            'brand' => $customer['sources']['data'][0]->brand,
            'last4' => $customer['sources']['data'][0]->last4
        ]);

        return $result;

    }

Even the Model static create method receives the right parameters. And I've taken care of the mass assignment also.

Upvotes: 2

Views: 1635

Answers (1)

Thomas Kim
Thomas Kim

Reputation: 15911

I posted this on Laracasts too :)

Anyway, you have to change your constructor to this:

public function __construct(array $attributes = []) {
    $this->gateway = StripeGateway;
    parent::__construct($attributes);
}

You are overriding the Model's base constructor, which changes its default behavior. Laravel uses the constructor for a lot of things (create method, relationships, etc.).

The base model's constructor function does several things, but one very important part of it is that it accepts an array to fill out its attributes as can be seen here:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

So, after you set your gateway property, you should call the parent's constructor function and pass the attributes.

Upvotes: 2

Related Questions