4

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 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I am looking at the documentation... the way I understand it, if I create a function in the model called getSomeFieldAttribute, I can call that in the application as some_field (as if it were a field from the database connected to that model)... am I understanding this correctly?
Yes, you got it r8 and also you can use any attribute of the model inside the getSomeFieldAttribute() function, using $this as $this->id
Laravel just keeps getting better. Thanks for your help.

Your Answer

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