0

I have a controller that should update an amount attribute and save it to a db. I can verify via getAmount that the model has the correct amount, but its not being saved to the database and no error is returned. Any idea what I'm doing wrong?

Here's my controller:

    $response = Input::json()->all();
    $ticket = Ticket::find($id);
    $ticket->setAmount($response['amount']);
    $ticket->getAmount(); //for debugging
    $ticket->save();
    return $ticket;

And my Ticket Model:

class Ticket extends \Eloquent {    protected $fillable = [];

    protected $amount = 0;

    function setAmount($amount){
        $this->amount = $amount*100000000;
    }

    function getAmount(){
        return $this->amount/100000000;
    }
}

1 Answer 1

1

Remove the $amount property from your Ticket class and it'll work.


BTW, you can also make this work with Eloquent's mutators:

class Ticket extends \Eloquent {

    protected $fillable = [];

    public function setAmountAttribute($amount)
    {
        $this->attributes['amount'] = $amount * 100000000;
    }
}

Then set it in your controller as you would any other property:

$ticket = Ticket::find($id);
$ticket->amount = $response['amount'];
$ticket->save();

and Eloquent will automatically call your setter function for you.

Sign up to request clarification or add additional context in comments.

2 Comments

That did it, thanks! What exactly was the problem here?
@AakilFernandes - Eloquent uses its own internal $attributes property to track the column values. When you try to set/get a non-existent property on your class, Eloquent will automatically resolve it to that internal $attributes array. Since you have set your own $amount property, that was being set instead of the amount index on the $attributes array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.