3

I want to assign a value to a variable in a laravel blade file based on condition.

<?php $status=''; ?>
      @if($user_role=='2'){
        <?php $status='1'; ?>
      }
      @elseif($user_role=='3'){
        <?php $status='2'; ?>
      }
      @elseif($user_role=='4'){
        <?php $status='3'; ?>
      }

but {{status}} returns nothing.How to assign a value to a variable in laravel 5.3 blade file

Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26
user3386779
  • 6,883
  • 20
  • 66
  • 134

2 Answers2

7
@if($user_role=='2')
  @php $status='1'; @endphp
@endif

@if($user_role=='3')
  @php $status='2'; @endphp
@endif

@if($user_role=='4')
  @php $status='3'; @endphp
@endif

you can check the value by adding echo

 @if($user_role=='4')
  @php echo $status='3'; @endphp
@endif
Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26
2

Switch Statement would be better

@switch($user_role)
    @case(1)
        @php $status = 1;@endphp
        or <h1>Status is 1</h1>
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
        @php $status = 5;@endphp
@endswitch

But most if not all of your logic should be done in a controller

https://laravel.com/docs/5.5/blade#switch-statements

if you don't have @switch available in your version of laravel you can always do

@php
 switch($user_role) {
  case 1:
      $status = 1;
      break;
  case 2:
      $status = 2;
      break;
 default:
     $status = 5;
}
@endphp
rchatburn
  • 732
  • 4
  • 13