I have been stuck with this problem for quite some time now. I have this particular array with the help of laravel's Socialite.
"first_name" => "xxx"
"last_name" => "xx"
"email" => "xxx@gmail.com"
"work" => array:2 [▼
0 => array:4 [▼
"employer" => array:2 [▼
"id" => "xxxxxxxxxxxxxx"
"name" => "FBI"
]
"location" => array:2 [▶]
"start_date" => "0000-00"
"id" => "496298904045521"
]
1 => array:6 [▶]
]
What I wanted to do is to get the first_name
, last_name
, email
and the name
from work
and save it in the database after. The problem is I can't seem to retrieve the name of work but instead gives me this error message
(1/1) ErrorException Undefined index: employer
How can I make this work? Quite lost here.
Controller
public function handleProviderCallback()
{
$usersocialite = Socialite::driver('facebook')->fields([
'first_name', 'last_name', 'email', 'work'
])->user();
//dd($usersocialite);
$findUser = Fbuser::where('email',$usersocialite->email)->first();
if ($findUser) {
Auth::login($findUser);
return view('home');
}else{
$user = new Fbuser;
$user->first_name = $usersocialite->user['first_name'];
$user->last_name = $usersocialite->user['last_name'];
$user->email = $usersocialite->user['email'];
$work=$usersocialite->user['work'];
$w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]);
$flattened = $w->flatten();
$flatten->all();
$user->work = $usersocialite->user[$flatten];
$user->save();
Auth::login($user);
return view('home');
}
}
you are accessing employer name in wrong way. you skip some indexes:
$w = collect([$work=>[$usersocialite->user['work'][0]['employer']=>[$usersocialite->user['work'][0]['employer']['name']]]]);
I can not understand what are you doing really. but I think you want something like this:
$w = collect(['work'=>[$work[0]['employer']=>[$work][0]['employer']['name']]]]);
To access the work name in the multidimensional array you can use something like this:
$user->work = $usersocialite->user['work'][0]['employer']['name'];
or you can use the Laravel helper function array_get
:
$user->work = array_get($usersocialite->user, 'work.0.employer.name');
The line above will replace the code:
$work=$usersocialite->user['work'];
$w = collect([$work=>[$usersocialite->user['employer']=>[$usersocialite->user['name']]]]);
$flattened = $w->flatten();
$flatten->all();
$user->work = $usersocialite->user[$flatten];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.