Skip to content
Advertisement

Laravel 8: How to style output at Models

I want to check if the status of users is Active or not. So in order to do this, I’ve added this piece of code to my Model User.php:

public function isActive()
    {
        if(($this->status) == 1)
        {
            return "<strong style='color:green'>Active</strong>";
        }
        else
        {
            return "<strong style='color:red'>Deactive</strong>";
        }
    }

And at the Blade, I get result by saying:

<td>{{ $user->isActive() }}</td>

But this will return this:

enter image description here

So the question is, how can I add some inline styles to the output of isActive() method ?

Advertisement

Answer

Generally you wouldn’t return markup from you model as you’re mixing concerns.

You would be ‘better’ using the value of your isActive() method in your blade view.

<td>
    <strong style="color:{{ $user->isActive() ? 'green' : 'red' }}">
        {{ $user->isActive() ? __('Active') : __('Inactive') }}
    </strong>
</td>

Your isActive() method would then just return a boolean value:

public function isActive()
{
    return $this->status == 1;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement