user3732216
user3732216

Reputation: 1589

Laravel and HTML images

What I am wanting to do is see if the user has a username and their avatar is in the avatars directory and if it is then display the HTML image but if its not I want it to display the default which is what I have below. I would like to see if someone can help me see what would be the best way so I don't have to have two HTML::image tags in my code.

@if(!empty($user->profile->username) && file_exists('/images/photos/avatars/'.$user->username))

@endif
{{ HTML::image('images/photos/profile-big.jpg', '', array('class' => 'img-circle img-offline img-responsive img-profile')) }}

Upvotes: 0

Views: 76

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25384

I would extract this to a method on e.g. the user model (or a user repository, or similar). Actually, "check for username" sounds like a method as well. And "has an avatar" does, too. That means two methods will need the avatar path, so that gets its own method too. For instance, like this:

public function hasUsername() {
    return empty($this->profile->username);
}

public function avatarPath() {
    return '/images/photos/avatars/' . $this->username;
}

public function hasAvatar() {
    return file_exists($this->avatarPath());
}

public function avatar() {
    return $this->hasUsername() && $this->hasAvatar()
        ? $this->avatarPath()
        : 'images/photos/profile-big.jpg';
}

Then, in your view, you can just do

{{ HTML::image($user->avatar(), '', array('class' => '...')) }}

I should stress that putting all of this in the model is perhaps not always what you'd like to do, although for a smaller project it is perfectly fine. But the idea of extracting smaller parts out to their own methods is rarely bad, especially when they contain separate pieces of logic.

Upvotes: 1

Related Questions