Multidimensional array Laravel 5.4 - php

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];

Related

Get value by column name value

Ny array looks something like this:
Illuminate\Database\Eloquent\Collection {#2052 ▼
#items: array:3 [▼
0 => App\Models\NewsMeta {#2089 ▶}
1 => App\Models\NewsMeta {#2090 ▶}
2 => App\Models\NewsMeta {#2091 ▶}
]
}
If I open up the array 2:
#original: array:7 [▼
"id" => 17
"post_id" => 240231
"news_tag_id" => 5
"meta_name" => "_thumbnail_id"
"meta_value" => "240232"
"created_at" => "2020-08-06 22:34:06"
"updated_at" => "2020-08-06 22:34:06"
]
Now, I looking to get value "240232" given that I've 240231.
How do I search inside array of the object?
Something like: where post_id is 240231 get ts meta_value.
FYI: It's not eloquent or DB query.
Something like this should work:
$postId = 240231;
$metaValue = null;
foreach ($collection as $model) {
if ($model->post_id == $postId) {
$metaValue = $model->meta_value;
break;
}
}
echo $metaValue;
You could also use the collection's seach method:
$postId = 240231;
$metaValue = $collection->search(static function($model, $key) use($postId) {
if ($model->post_id == $postId) {
return $model->meta_value;
}
});
echo $metaValue;
You can use the collection firstWhere() method
$collection->firstWhere('post_id', '240231')['meta_value'] ?? null;
With the data you provided this should return 240232. In a dataset where there is no post_id = 240231 it would return null.

Eloquent duplicating rows when saving to database - laravel

I am having this issue when ever I save to the database the row gets duplicated even if the array contains one index position. Am I missing something here?
foreach($params['service'] as $key => $value){
$data['name'] = $value;
$data['price'] = $params['price'][$key];
$data['business_id'] = $params['business_id'];
$service = new Service($data);
$service->save();
}
data of $params
array:5 [▼
"business_id" => "1"
"service" => array:1 [▼
0 => "web development"
]
"price" => array:1 [▼
0 => "R4500"
]
"submit" => null
]
these are the duplicates
1 web development R4500 1 2018-08-30 07:24:34 2018-08-30 07:24:34
2 web development R4500 1 2018-08-30 07:24:34 2018-08-30 07:24:34
unfortunately the answer provided by #Rathod also produces duplicates but I noticed that when I add multiple data to the array as shown below it saves without duplicates.
array:5 [▼
"business_id" => "1"
"user_id" => "1"
"service" => array:3 [▼
0 => "web development"
1 => "mobile development"
2 => "internet marketing"
]
"price" => array:3 [▼
0 => "R4500"
1 => "R8900"
2 => "R5600"
]
"submit" => null
]
here's the full function
public function createService(array $params) : Service
{
// dd($params);
try {
foreach($params['service'] as $key => $value){
$service = new Service();
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
return $service;
} catch (QueryException $e) {
throw new CreateServiceInvalidArgumentException($e->getMessage(), 500, $e);
}
}
Try following simple way:
foreach($params['service'] as $key => $value){
$service = new Service();
$service->name = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
I hope it works fine.
Those moments I want to slap myself for being stupid... I just noticed I was sending the same data via ajax.. I must have forgotten I had done that.Thanks a lot to everyone for taking your time to look at this for me.

Creating new Associative collection and adding new items in laravel

Here's my sample code.
$users = 3 users //suppose
$leaders = new Collection();
foreach($users as $user)
{
$name = $user->name;
$username = $user->username;
$leaders->put('name', $name);
$leaders->put('username', $username);
}
dd($leaders);
This gives me the result for only one user (The 3rd user)
Collection {#274 ▼
#items: array:2 [▼
"name" => "user3"
"username" => "username3"
]
}
Because put() is replacing the values with the same keys.
I tried with this too:
$leaders->push($name);
$leaders->push($username);
But I am getting:
Collection {#274 ▼
#items: array:6 [▼
0 => "user1"
1 => "username1"
2 => "user2"
3 => "username2"
4 => "user3"
5 => "username3"
]
}
How to create different item arrays for different users?
Update #1: Got the answer.
Now trying to display the values on the view like this:
#foreach($leaders as $leader)
{{ $leader->username }}
#endforeach
Error: Trying to get property of non-object.
Is this not supposed to work this way for custom collections?
Update #2: Nevermind. Found it.
It is supposed to work this way: {{ $leader['username'] }}
Just try push method
foreach($users as $user)
{
$leaders->push([
'name' => $user->name,
'username' => $user->username,
])
}

INSERT IGNORE unique email laravel 5.4

I am using the maatwebsite to import excel to db and
$dataArray[] =
[
'name' => $row['name']
'email' => $row['email'],
];
Apprentice::insert($dataArray);
When the variable is printed the result is:
array:2 [▼
0 => array:18 [▼
"name" => "Maicol Stiven"
"email" => "maic1ce#live.com"
]
1 => array:18 [▼
"name" => "Cristian Camilo"
"email" => "carin45#gmail.com"
]
]
the email is a unique, I need when the email is duplicated, omit it and insert the other records
How can I do it? thanks
Use the firstOrNew method like so
$a = Apprentice::firstOrNew(['email' => $row['email']]);
$a->name = $row['name'];
$a->save();

Laravel add new array key to eloquent insert

I am trying to add a user_id array key when doing an eloquent insert. I have the following setup:
View
{!! Form::label('supervisors', 'Assign Supervisor(s)') !!}
{!! Form::select('supervisors[][supervisor_id]', $supervisors, null, ['class' => 'chosen-select', 'multiple']) !!}
User Table
id first_name
12 John
UserSupervisors Table
id user_id supervisor_id
1 12 1
Currently the request $request->get('supervisors') outputs this:
array:1 [▼
0 => array:1 [▼
"supervisor_id" => "1"
]
]
However, I would like it to output this:
array:1 [▼
0 => array:1 [▼
"supervisor_id" => "1",
"user_id" => "12"
]
]
How can I achieve this dynamically?
You can easily use this code to solve the problem:
$user = new User();
$user->user_id = 10;
$user->supervisor_id = Input::get('supervisor_id');
$user->save();
to add an item to the Request $request, you can use merge() like this :
$user_id = 4; //your user id
$request->merge([supervisors => ["user_id" => $user_id]]);
and $request->get('supervisors') will give you the output you need
hope that helps

Categories