0

I have a field to that is retrieved from the database which contains the filename of an image.

If that field is NULL, I'd like to set it to 'default_image.jpg'. This image gets referenced on many pages through many controllers, so I just want the value to default when getting retrieved.

Can someone please tell me how to do this.

Joe
  • 61
  • 7
  • I've seen that post and I can't get it to work that way - not sure what I'm doing wrong. – Joe Jun 26 '14 at 13:01

1 Answers1

4

Accessors are what you are looking for. As the name states Accessors will be called whenever you try to access that certain property on the eloquent model.

<?php

class MyModel extends Eloquent {

    public function getImageAttribute($value)
    {
        if(is_null($value))
            return 'default_image.jpg';

        return $value;
    }

}

Update:

Just for clarification reasons: When you try to access attributes that do not exist on a class, PHP invokes the __get() magic method (if it does exist), instead of complaining.

Eloquent works exactely the same way. When __call() is invoked (remember, attributes you call on an eloquent model do not really exist) laravel will give you the value of that field from your database. The trick comes in here.

When the __get() method is called on an eloquent model. Eloquent will call it's getAttribute() method which grabs the attribute but checks if an accessor exists beforehand (in laravel source accessors are called get mutators). You can see it here.

If that's the case laravel calls the mutateAttribute() method on the given key. The mutateAttribute() will then eventually call the getXAttribute (source) where X is the name of the attribute being accessed.

That's the whole trick behind the magic that's going, and again shows how well structured laravels source is.

thpl
  • 5,810
  • 3
  • 29
  • 43
  • So that means I have to call getImageAttribute each time? – Joe Jun 26 '14 at 12:58
  • @Joe nope. Accessors are automagic. Those are automatically called by laravel everytime you're trying to access the property on that model. You'll just need to implement that Accessor and you can go on using `$mymodelinstance->image`. – thpl Jun 26 '14 at 13:02
  • You mean $mymodelinstance->getImageAttribute ? – Joe Jun 26 '14 at 13:06
  • @Joe no you just access your property as you are used to. That's the cool thing about accessors and mutators :) – thpl Jun 26 '14 at 13:13
  • 1
    Ok, I got it... thanks Thomas! :) – Joe Jun 26 '14 at 13:31
  • @Joe I've added some further clarification just to make clear what's going on behind the scenes – thpl Jun 26 '14 at 13:58