You have wrong order of parameters in in_array
if (in_array($permission, $role->permissions)) {
//
}
By the way I recommend to you use this package
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
The Below code in middleware is working fine when user has role_id 1, When I did the dd on role->permissions I get then the response is array.
But on this line
if (in_array($role->permissions, $permission)) {
I get this error for all other users whose role_id is different
in_array(): Argument #2 ($haystack) must be of type array, string given
My Roles Model has
protected $casts = [
'permissions' => 'array',
];
My User Model has
protected function role()
{
return $this->hasOne(Roles::class, 'id', 'role_id');
}
My web Middlewaregroup has
\App\Http\Middleware\RolePermissionCheck::class,
My Meddlware has
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
class RolePermissionCheck
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!empty(Auth::user()->role_id)) {
$role = Auth::user()->role;
Gate::before(
function () {
if (Auth::user()->role_id === 1) {
return true;
}
}
);
// dd($role->permissions);
foreach ($role->permissions as $permission) {
Gate::define(
$permission,
function ($role) use ($permission) {
if (in_array($role->permissions, $permission)) {
return true;
}
}
);
}
}
return $next($request);
}
}
Please or to participate in this conversation.