0

first of all, the question is not about the solution, but about the best practice.

my blade is:

@if (!empty($amount))
     <div class="amount {{$color}}">
          {{$amount}}
     </div>
@endif

color class is defined in service by amount. But I can bet, that is bad architectural solution.

So I need an advice for the best practice in laravel for customizing blade class.

3
  • this is bad? im using this technique. it's interesting if anyone can make a better suggestions. Commented Dec 18, 2018 at 6:06
  • what about using custom laravel directive? Commented Dec 18, 2018 at 6:15
  • thanks for that Martynas, but im still just using it like so: @ php $bgcolor = {{ $record->amount ? 'success' : 'danger' }} @ endphp then <div class="bg-{{$bgcolor}}"></div> . so this will suffice for now since it is not that complicated. i think that you shouldnt feel guilty using this technique if the logic was very simple (wink) Commented Dec 18, 2018 at 6:42

1 Answer 1

1

I would calculate the color level ($color in your example) where you assign $amount to the blade template (most likely in a controller). You can do this with if/elseif/else where you set colors depending on your limits (e.g. $amount < 5 is green, $amount < 10 is orange, $amount < 20 is red).

It is best practice to separate design from logic, therefore I won't recommend to add logic to you blade template - even if it is a one-liner.

If that's the way you have it right now then I'd keep it this way.

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

4 Comments

data is assigned in view composer. So I added additional parameter there. But I have another tricky question - where I should put method to return that class name by amount (e.g. $amount < 5 is green, $amount < 10 is orange, $amount < 20 is red) ?
I'm a big fan of the "Repository Design Pattern". For example I have a UserController and respectively a UserRepository. So my controller has a function call to the UserRepository ($userRepository->calculateSomething()) and nothing more. I have almost no logic in my controllers - everything is in my repositories.
but what if you're inside the foreach loop on the blade file?
In the blade foreach-loop you are outputting data for each element of a (hopefully previously prepared and to the view assigned) array/object. It doesn't matter if you have one or many colors. It only depends on your data structure.

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.