Why use unless in Laravel instead of a no if denial?

Asked

Viewed 468 times

3

I think the Laravel an interesting framework. The features of the view are excellent, regarding the simplification of the syntax of a foreach or iffor example.

But still one thing I don’t understand is: Why the unless?

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

What are the benefits of Blade accepting a @unless?

Is there any case that it is more beneficial to use it than a @if in denial?

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
  • 2

    syntax Uggar only =D Laravel is full of it

  • Honestly, for me, it was not easy to read. There was a replacement of a known operator (!) by a less common (unless) method. In my opinion, a function has to bring more than just better "reading", should bring performance benefits (lambda, for example), simplify declarations by reducing the amount of code (foreach, warn...) and so on.

1 answer

5


I don’t program in PHP, I know the unless for programming in Ruby.

As you may have noticed:

unless is the inversion of if, so instead of you making a if on a denied condition, if it makes more sense for the readability of the code, you make a unless on the natural condition, without needing 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 nay for an administrator, "you are not an administrator".

It’s just a matter of semantics, and if you’re used to using the command, you might find that in some cases reading the code sounds better with unless than with if not.

However the code with unless can get hard to read if you abuse it, how to use it to test a denied condition (it is already the negation of the condition!) or use it in conjunction with Else.

  • Thank you for the reply. Although it is not about Laravel, the subject addressed represents very well the scenario that the unless is used. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.