1

I Have a User model with the property is_active. When i'm inside a foreach loop, I don't want to use the following: echo if ( $user->is_active == 0 ) 'not active' : 'active'

What will be the best way to implement this? write a isActive() method on the User model and place the logic there?

1
  • 1
    Use a presenter for such things. You could also do it with an accessor, but I wouldn't. Commented Apr 7, 2015 at 13:03

1 Answer 1

2

There are a few approaches that you can take.

Approach 1: Acessor!

Create on your model:

public function getFormattedActiveMethod() {
    return $this->attributes['active'] ? 'active' : 'not active';
}

And then you can use it like: $user->formattedActive (or whathever you want to call it, as long your method name matches getCamelCaseNameAttribute()).

You can also add this attribute into the $appends property array, so it will show up when you cast the model to array/json.

Approach 2: Presenter Pattern

Simply create a new class just to present data to your views. It's a good approach to prevent the Model from bloating and also separate your logic. There are a few packages that helps you to achieve it, like robclancy/presenter, laracasts/Presenter, ShawnMcCool/laravel-auto-presenter and even League's Fractal, that can help you building a consistent API too. Depending on the size of your project, it's better to take this approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.