Laravel - Dynamically add field to model and prevent its save

Viewed 412

I need to add a field to a model, and this field is not a real column, for example:

function calculateDiscount(Order $order)
{
  // some logic
  $order->discount = 20; // It's just an example
  return $order
}

The field discount is not a real column to database. I need to add this "dynamic" field to use later.

If I perform a save like:

$order->save();

I get the error:

Column not found: 1054 Unknown column 'discount' in 'field list' (SQL: update `orders` set `discount` = 20, where `id` = 67586)

There is a way to add a "dynamic" field and prevent Laravel save it ?

1 Answers

use appends

Models/Order.php

class Order extends Model {
    protected $appends = [
        'discount'
    ];

    public function getDiscountAttribute() {
        // your logic of how to get discount value
        return $discount;
    }
}

or you can load the discount attribute only when you need

// controller
$order->append('discount'); // load the value

// model
class Order extends Model {
    public function getDiscountAttribute() {}
}
// add the getDiscountAttribute function only
Related