Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,


1 Answers

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);

$checkout->some_extra_field;
like image 84
Amit Gupta Avatar answered Oct 30 '25 03:10

Amit Gupta