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,
])
}
Related
in this result:
LengthAwarePaginator {#251 ▼
#total: 2
#lastPage: 1
#items: Collection {#246 ▼
#items: array:2 [▼
0 => ProductCategories {#247 ▼
...
#attributes: array:6 [▼
"id" => 1
"category_name" => "test"
"lang" => "fa"
"images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
"created_at" => "2017-12-08 10:47:56"
"updated_at" => "2017-12-08 12:27:10"
]
#original: array:6 [▼
"id" => 1
"category_name" => "test test"
"lang" => "fa"
"images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
"created_at" => "2017-12-08 10:47:56"
"updated_at" => "2017-12-08 12:27:10"
]
...
}
1 => ProductCategories {#248 ▶}
]
}
which i get from this query:
$categories = ProductCategories::paginate(10);
dd($categories);
i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:
{{$categories->images->thumbnail}}
but i get Undefined property error and i can't show that
How about you just cast that field to an array ...
class ProductCategories ...
{
protected $casts = [
'images' => 'array',
];
...
}
#foreach ($categories as $category)
{{ $category->images['thumb'] }}
#endforeach
Laravel 5.5 Docs - Eloquent - Mutators - Array and Json Casting
The variable $categories is a Collection, so you need to get each individual object to get its data. For this you'll need to use a foreach.
#foreach($categories as $category)
{{ $category->images }}
#endforeach
And to have access to thumbnail you'll need to decode the json string that you have in images. For that, you can use json_decode($category->images) function. This will return an array with thumbnail as key.
If you want to make it right, you should keep image related data in a separate table and use a relationship between category and image:
public function images()
{
return $this->hasMany(Image::class);
}
But since you're keeping images data as JSON string, the first thing you want to do is to cast it to array. Add this to the model:
protected $casts = [
'images' => 'array',
];
Then in Blade view:
#foreach ($categories as $category)
{{ $category->images['thumbnail'] }}
#endforeach
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];
I am passing a variable $mailchimp from my Controller to my View.
this is what I got with {{dd($mailchimp)}}
array:8 [▼
"id" => "xyz123"
"email_address" => "john.doe#discworld.com"
"unique_email_id" => "c9a36649c8"
"email_type" => "html"
"status" => "subscribed"
"merge_fields" => array:2 [▼
"FNAME" => "John"
"LNAME" => "Doe"
]
"stats" => array:2 [▼
"avg_open_rate" => 0
"avg_click_rate" => 0
]
"list_id" => "769808qeqw92"
]
how can I loop through this array ($mailchimp) ? With the code below I get an exception: "htmlentities() expects parameter 1 to be string, array given"
#foreach($mailchimp as $user)
#if(is_array($user))
#foreach($user as $key => $value)
{{$value}}
#endforeach
#endif
#endforeach
Update:
With this Code in My Controller
public function index()
{ //Fetch all subscribers from DB
$subscribers = Subscriber::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->get();
foreach ($subscribers as $key => $subscriber) {
//Check if the local subscriber is also present in mailchimp
$mailchimp = Newsletter::getMember($subscriber->email);
}
return view('backend.newsletter.contacts.index')->withSubscribers($subscribers)
->withMailchimp($mailchimp);
}
I need to iterate the mailchimp array. As there are multiple users, alexey's suggestion doesn't work out anymore.
This stil doesn't work:
#foreach($mailchimp as $key => $user)
{{$user}}
#endforeach
You don't need to iterate over $user. If $mailchimp is an array of users, do this:
{{ $mailchimp['email_adress'] }}
{{ $mailchimp['merge_fields']['FNAME'] }} {{ $mailchimp['merge_fields']['LNAME'] }}
Since you are only interested in printing the values in your array, you can use array_flatten to get rid of the nested arrays, and then loop through the result:
#foreach(array_flatten($mailchimp) as $userData)
{{$userData}}
#endforeach
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
Here is what I try to do:
$q = Question::where('id',$id -> id)->get();
$q[] = $q->push([ 'test' => true]);
dd($q);
This will output:
Collection {#220 ▼
#items: array:3 [▼
0 => Question {#225 ▶}
1 => array:1 [▼
"test" => true
]
2 => null
]
}
So 'test' => true will append as a new key, but I want to insert it in Question so latter I can access to it like this with foreach $q -> test
So here is how I want access to item:
#foreach($q as $qq)
{{ $qq->test }}
#endforeach
It can be done by using setAttribute() function of Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
As You can see it stores data in protected $attributes using setAttribute(), and when we do $SomeModel->some_field it uses magic method __get() to retrieve item by association from attributes array.
Here is the resolution to Your question:
$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
Apart from setAttribute(), you can use put() refer to this post for one item. And map() for many items, refer to this post.