Yahya Uddin Yahya Uddin - 5 months ago 13
PHP Question

How to define an accessor for an existing field in a model in Laravel 5?

I have a model called

Book
for a table called
books
, that has a field called
cover_image
.

However, I want to define an accessor for the field
cover_image
instead of just retrieving the default value.

This is how I attempted to do this:

class Book extends Model {

public function getCoverImageAttribute() {

if ($this->cover_image === null) { // Not sure how to check current value?
return "a.jpg"
}
return $this->cover_image;
}

}


However the above of course does not work because calling
$this->cover_image
again would cause recursion

How can I fix this?

Answer

You must check for the attribute instead:

class Book extends Model {

    public function getCoverImageAttribute() {    

         if ($this->attributes['cover_image'] === null) {
               return "a.jpg"
         }
         return $this->attributes['cover_image']; 
    } 

}

This will allow you to normally use $book->cover_image as well.

I believe the following example will also work:

class Book extends Model {

    public function getCoverImageAttribute($value) {    

         return is_null($value) ? 'a.jpg' : $value; 
    } 

}
Comments