How to use in_array function in Laravel Blade Template

In this tutorial we are going to share how to use in_array php function in laravel blade view file. Mostly when the beginners use the to check if the veriable values exits in an array to select that option in select box or any other we need to in_array function use in laravel blade file.

Bellow we have describe easy way to use in_array syntax and how to send the array from laravel controller and how to use the in_array function in laravel balde.

in_array Function in php Example

We use the in_array in php just like below code. Here in in_array first argument is which variable which we want to exits or not in our array and second is our array. We can compare one or more in first argument.

<?php
$people = ["Peter", "Joe", "Glenn", "Cleveland"];

if (in_array("Joe", $people))
  {
      echo "Match found";
  } else  {
      echo "Match not found";
  }
?>

in_array Function use in Laravel Blade

Here is the example to use in_array in laravel blade file.

@php 
    $roles = ['admin', 'user', 'client', 'doctor', 'nurse'];

    $userRole = ['doctor', 'user']; //We can add multiple here
@endphp

@if (in_array($userRole, $roles))
     <span>Something</span>
@endif

in_array use in Laravel Blade File Code Example

Here we will lean your full example of use in_array in laravel balde file. First we send the array and arguments from laravel controller then check how we use the in_array function for checking is the user have those roles then they are selected in select box.

In Controller:

public function edit($id)
{
    $user = User::find($id);
    $roles = Role::get(['id', 'name']);
    $userRoles = $user->roles->pluck('id')->toArray();

    return view('admin.users.edit', compact('user', 'roles', 'userRoles'));
}

In Blade File:

<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Role:</strong>
        <select class="custom-select custom-select-lg mb-3" name="roles[]" multiple>
          <option selected>Select Role</option>
          @foreach($roles as $role)
            <option value="{{ $role->id }}" @if(in_array($role->id, $userRoles) ) selected @endif> {{ $role->name }} </option>
          @endforeach
        </select>
    </div>
</div>

I hope this example help you more…

Leave a Comment