Jun 11, 2020
0
Level 9
How to Assign Roles Senior Manager Role using manager_id
In my Laravel-5.8, I have this API which I tried to consume and save using Guzzle
[
{
"date_of_birth": "2009-11-21T00:00:00",
"first_name": "JAGUA",
"last_name": "KING",
"staff_id": "44444",
"senior_manager_id": "98876",
},
{
"date_of_birth": "2005-11-21T00:00:00",
"first_name": "JACKIE",
"last_name": "LEE",
"staff_id": "44444",
"senior_manager_id": "2222",
},
]
Command
namespace App\Console\Commands;
use Illuminate\Console\Command;
public function handle()
{
$client = new Client();
$res = $client->request('GET','https://api.employees.net/allemployees', [
'query' => ['key' => 'dfffgggggffffff']
])->getBody();
$clientdatas = json_decode($res->getContents(), true);
foreach($clientdatas as $clientdata)
{
Employee::updateOrCreate([
'employee_code' => $clientdata->staff_id,
],
[
'first_name' => $clientdata['first_name'],
'last_name' => $clientdata['last_name'],
'date_of_birth' => Carbon::parse($clientdata['date_of_birth'])->toDateString(),
'senior_manager_id' => $clientdata['senior_manager_id'],
]);
$user = User::updateOrCreate([
'email' => $employee->email,
],
[
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
'senior_manager_id' => $employee->senior_manager_id,
]);
if (! $user->hasRole('Employee')) {
$user->assignRole('Employee');
}
}
}
From the code above, I have assigned Employee Role to each of the user using $user->assignRole('Employee').
However, I want to loop through all the the user table after I have saved all the data, check the field senior_manager_id in $user = User, and Assign the Role 'Senior Manager' $user->assignRole('Senior Manager') to the user where id = senior senior_manager_id.
if (! $user->hasRole('Senior Manager')) {
$user->assignRole('Senior Manager');
}
This should only be done if it doesn't exits
How do I achieve this?
Thanks
Please or to participate in this conversation.