assign a value to a variable in blade file

10,295

Solution 1

@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

Solution 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
Share:
10,295
user3386779
Author by

user3386779

Updated on June 28, 2022

Comments

  • user3386779
    user3386779 3 months

    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