aserwin aserwin - 1 year ago 153
PHP Question

Laravel Models - add non-database field

I have a model in Laravel called Checkout. It is just tied to a table in the database called checkouts.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Checkout extends Model
protected $primaryKey = 'id';
protected $table = 'checkouts';

What I would like to do is add a field to the model that isn't a field in the table. Is this even possible?

If need be, I will completely manually build the model, but I have never seen any examples of that either.

Any help would be greatly appreciated! Thanks,

Answer Source

You can use Laravel's Accessor as:

public function getSomeExtraFieldAttribute()
    return 2*4; // just for exmaple

Then you can access it using

$checkout = App\Checkout::find(1);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download