Reputation: 2706
I have an eloquent model with a boolean field. The column in the database is a tinyint(1)
and the value is stored correctly as 1
. If I access this value in any given context outside the class I get the correct value:
$myModel = MyModel::first();
var_dump($myModel->visible); //outputs 1
When I access it inside a method inside the model class though....
class MyModel {
public function isVisible(){
var_dump($this->visible);
// return $this->visible && $this->approved; // another true value
}
}
//on tinker
>> $myModel->isVisible();
array(0) {
}
>>
I know this sounds crazy but I've been at it for two hours and cannot make it work. What am I missing?
Upvotes: 0
Views: 547
Reputation: 15931
Laravel's Model class already has a protected $visible
property. As you might have guessed, it's an array. When accessed from within the class, it has access to this protected
property so it will return the array. When accessed outside the class, it uses PHP's magic __get
method so it's returning the value of your column.
If possible, you could rename your column to prevent any potential future conflicts. Otherwise, you can change your isVisible()
method by using the getAttribute
method to access the model's column value rather than accessing the model's property like this:
public function isVisible(){
return $this->getAttribute('visible') && $this->approved;
}
Upvotes: 5