Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Binapick's avatar

Curl && Middleware

After a successful login, which has to be done using curl, I get the following back:

{
  "token": "xxxxxxx-6d48-4130-8587-a832cd58f4f0",
  "userInfo": {
    "uuid": "b66e43bf-3d57-4457-be97-1c0aa53fc3db",
    "email": "[email protected]",
    "firstname": "Tom",
    "lastname": "Eshford",
    "language": "EN",
    "roles": [
      "ADMINISTRATOR",
      "USER"
    ]
  }
}

now the roles would have to be checked using middleware so that the user can work according to his roles. However, I don't have the complete approach for it. How do I get this data into the middleware? The examples I find on the internet always refer to a DB that is used by Laravel using Eloquent.

Andreas

0 likes
2 replies
LaryAI's avatar
Level 58

To get the user roles from the response data and pass it to a middleware in Laravel, you can follow these steps:

  1. Create a middleware class using the following command:
php artisan make:middleware CheckUserRole
  1. Open the app/Http/Middleware/CheckUserRole.php file and modify the handle method as follows:
public function handle($request, Closure $next)
{
    $response = $next($request);

    // Get the response data
    $responseData = json_decode($response->getContent(), true);

    // Check if the response data contains the "roles" key
    if (isset($responseData['userInfo']['roles'])) {
        $roles = $responseData['userInfo']['roles'];

        // Perform your role-based checks here
        // For example, you can check if the user has the "ADMINISTRATOR" role
        if (in_array('ADMINISTRATOR', $roles)) {
            // User has the "ADMINISTRATOR" role
            // Perform the necessary actions
        }
    }

    return $response;
}
  1. Register the middleware in the app/Http/Kernel.php file by adding it to the $routeMiddleware array:
protected $routeMiddleware = [
    // Other middleware...
    'checkUserRole' => \App\Http\Middleware\CheckUserRole::class,
];
  1. Apply the middleware to the routes or route groups where you want to perform the role-based checks. For example:
Route::group(['middleware' => 'checkUserRole'], function () {
    // Routes that require role-based checks
});

By following these steps, the CheckUserRole middleware will intercept the response, extract the user roles from the JSON data, and perform the necessary role-based checks. You can modify the middleware's logic to suit your specific requirements.

Binapick's avatar

@LaryAI The $routeMiddleware var did not exist in my kernel.php file. Should i create this var or add it to $middlewareAliases?

Please or to participate in this conversation.