Failed to get attributes in accessor method - laravel eloquent

Ok, I want to have a custom field that doesn't exist as a column in my db table.

I followed the last part: http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

My model code:

class Car extends Eloquent{
    protected $fillable = array('driverID', 'fuelRemaining');
    protected $appends = array('is_driver');

    public function user(){
        return $this->belongsTo('user');
    }

    public function getIsDriverAttribute(){
        return ($this->attributes['driverID'] == Auth::user()->id);
    }
}

      

Car table:

Schema::create('cars', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('driverID');
        $table->integer('fuelRemaining');
        $table->mediumtext('desc');
        $table->timestamps();
    });

      

As you can see, I need to return an extra field, which is "is_driver", but when I run it, this field is used to determine if the current signed user is the driver itself by comparing IDs.

it will throw this error:

Undefined index: driverID

      

Not sure what I am doing wrong here, please advice.

+3


source to share


1 answer


And I found why. This is a link for future readers.

In my controller I only get these two

$car = Car::where('fuelRemaining', 0)->get(array('id', 'desc'));

      



When I added authorID to get array

$car = Car::where('fuelRemaining', 0)->get(array('id', 'desc', 'authorID'));

      

I can get the authorID attribute on my custom accessory mentioned in the question.

+5


source







All Articles