Why use unless in Laravel, instead of a negation in if?

2

I find Laravel an interesting framework. The functionality of the view is excellent, for simplifying the syntax of a foreach or if for example.

But one thing I did not understand is: Why does unless ?

Why use @unless if you can simply make a @if(! $expressao) ?

What are the benefits of Blade accepting a @unless ?

Is there a case that is more beneficial to use than a% with negation?

Example:

 @unless(Auth::user()->admin)
     <div>Você não é administrador</div>
 @endunless

 {{-- aqui é menos código, não acham? --}}
 @if(!Auth::user()->admin)
     <div>Você não é administrador</div>
 @endif
    
asked by anonymous 26.04.2016 / 22:41

1 answer

4

I do not program in PHP, I know unless for programming in Ruby.

As you may have noticed:

  

if is the inversion of if , then instead of you doing an if on a denied condition , if it makes more sense for the readability of the code, you do a unless on the natural condition, without having to deny it.

Let's read your first example:

  

Unless you are an administrator, "you are not an administrator."

Let's read your second example:

  

If you are not an administrator, "you are not an administrator."

It's just a matter of semantics, and if you're used to using the command, you may find that reading the code sometimes sounds better with unless than with if not .

However, unless can be difficult to read if you abuse it, such as using it to test a denied condition (it is already denial of the condition!) or using it together with else .

    
28.04.2016 / 16:24