skip to Main Content

I received this error in app/Http/Middleware/StaffAccess.php:22

$staff = Auth::guard('admin')->user();

$staffAccess = $staff->staff_access;

if (in_array($access, $staffAccess))
{
    return $next($request);
}

When I tried to login in dashboard as admin and redirect in dashboard I received this error

in_array() expects parameter 2 to be array, null given

Admin Model:

class Admin extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    // protected $casts = ['access'=>'array'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    
    protected $casts = [
        'staff_access' => 'object',
    ];
}

2

Answers


  1. Its because your $staffAccess is null. So the program turn an error because in_array expect parameter to be array.

    You can check the contains of $staffAccess or you can give a condition where $staffAccess == null, so if $staffAccess is null the program won’t able enter your return $next($request);. You can check it with is_null

    $staffAccess = $staff->staff_access;
    if(!is_null($staffAccess)) { // or you can check with ($staffAccess === null)
     if(in_array($access, $staffAccess)){
        return $next($request);
     }
    } else {
     // your other code
    }
    
    Login or Signup to reply.
  2. You need to check the array for its presence. You can make it a condition or a ternary operator:

    $staff = Auth::guard('admin')->user();
    
    $staffAccess = $staff->staff_access;
    
    if (in_array($access, $staffAccess ?? []))
    {
        return $next($request);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search