mario
mario

Reputation: 443

Blade inline if and else if statement

Is there a syntax to specify inline if and else if statement in Laravel blade template?

Normally, the syntaxt for if and else statement would be :

{{ $var === "hello" ? "Hi" : "Goodbye" }}

I would now like to include else if statement, is this possible?

 {{ $var === "hello" ? "Hi" : "Goodbye" else if $var ==="howdie ? "how" : "Goodbye""}}

Upvotes: 43

Views: 96577

Answers (6)

Bilal Ahmad
Bilal Ahmad

Reputation: 1

$pandit->pandit_id != (auth()->user() ? "not pandit" : (auth()->guard('pandit')->user() ? auth()->guard('pandit')->user()->id : "vendor"

Upvotes: 0

Ehsan Jafari
Ehsan Jafari

Reputation: 41

with this code you can write single line if-else laravel blade with four condition.

{
  {
    $a == 10
      ? "10"
      : $a == 20
      ? "20"
      : $a == 30
      ? "30"
      : $a == 40
      ? "40"
      : "nothing";
  }
}

Upvotes: 0

M.Elwan
M.Elwan

Reputation: 1944

remember not every short code is a good one. in your example there's no single way to hit this else if because you're saying

if($var === "hello")
    { 
        // if the condetion is true
        "Hi";
    }
else
    { 
        // if the condetion is false
        "Goodbye";
    }
// error here
else if($var ==="howdie")
    { "how"; }
else
    { "Goodbye"; }

this's wrong you can't use two elses respectively. you've structure your conditions like

if (condition) {
    # code...
} elseif (condition) {
    # code...
} else {

}

the same in the ternary operators

(condition) ? /* value to return if first condition is true */ 
: ((condition) ? /* value to return if second condition is true */ 
: /* value to return if condition is false */ );

and beware of (,) in the second condition.

and as you see your code is just going to be tricky, unreadable and hard to trace. so use the if else if if you've more than one condition switching and revise your logic.

Upvotes: 8

YoJey Thilipan
YoJey Thilipan

Reputation: 687

<select id="days" class="Polaris-Select__Input" name="days" aria-invalid="false">
    <option value="10" @if($settingsData->days == "10") selected @endif >at 10 Days</option>
</select>

@if($settingsData->days == "10") selected @else not selected @endif

Upvotes: 6

MoPo
MoPo

Reputation: 1551

You can use this code in laravel blade:

{{  $var === "hello" ? "Hi" : ($var ==="howdie ? "how" : "Goodbye") }}

Upvotes: 81

rahul
rahul

Reputation: 506

I believe that is two if else statements in one line. I cant imagine way to make it inline but i would have done something like this.

@if($var=="hello" || $var=="Hi")
   {{$var === "hello" ? "Hi" : "Howdie"}}
@else
   {{"Goodbye"}}
@endif

Upvotes: 0

Related Questions