How do I get the key from a collection item?
$posts= Post::all();
Example (doesn't work):
$key = $posts->where('id', $id)->getKey();
The all() will return a collection without keys. If you're talking about integer keys like 0, 1, 2 etc, use the search() method:
$key = $posts->search(function($i) use($id) {
return $i->id === $id;
});
Try $post_ids = Post::pluck('id');
That grabs just the id column from all the Post records and returns them as a collection.
If you want just a plain array, add toArray():
$post_ids = Post::pluck('id')->toArray();
Related
I'm trying to sort an array of objects in Laravel, I set my current foreign key value of my post categorie_id to come first in the array.
After that, the other objects need to be filtered in desc order.
Code:
$categorie = Categorie::all()->sortBy($posts->categorie_id);
This does not quite work the array stays the same.
In this case, my VIEW has a post with a foreign key of 4
$categorie = Categorie::with(['posts' => function ($q) {
$q->orderBy('categorie_id', 'desc');
}])->find($categorie_id);
// when lazy loading
$categorie = Categorie::find($categorie_id);
$categorie->load(['posts' => function ($q) {
$q->orderBy('categorie_id', 'desc');
}]);
// or on the collection
$categorie = Categorie::find($categorie_id);
$categorie->posts->sortByDesc('categorie_id');
// or querying students directly
$categorie = Categorie::whereHas('posts', function ($q) use ($categorie_id) {
$q->where('id', $categorie_id);
})->orderBy('categorie_id')->get();
I'm trying to return all the attributes from my database that have a set foreign key (Attribute groups). I've set up all the relationships in my model but I'm unsure how to query these relationships using a collection or array.
AttributeGroup -
public function attribute()
{
return $this->hasMany('App\Attribute', 'group_id');
}
Attribute -
public function attributeGroup()
{
return $this->belongsTo('App\AttributeGroup');
}
My current query -
$page = Page::where('slug', $slug)->firstOrFail();
$groups = AttributeGroup::where('page_id', $page->id)->get()->toArray();
$atts = Attribute::where('group_id', $groups[0]['id'])->get();
This works because we have set the specific index of the array using $groups[0]
Is there a simple way I can pass an array through to the query using their relationships or is looping through the results and then passing my own array to the query the best approach?
$attributes = array();
foreach ($groups as $group){
array_push($attributes, $group['id']);
}
$atts = Attribute::where('group_id', $attributes)->get();
$groups is a collection. Assume them as arrays on steroids. Therefore you can use the pluck() method to get those ids you need:
$page = Page::where('slug', $slug)->firstOrFail();
$groups = AttributeGroup::where('page_id', $page->id)->get();
$atts = Attribute::where('group_id', $groups->pluck('id'))->get();
Also if you've set your relationships correctly, you should be able to loop through $groups and access the attributes of those $groups. You can test it:
$groups = AttributeGroup::where('page_id', $page->id)->get();
dd($groups->first()->attributes);
Let's say I have a model collection that I'm mapping through like this:
$alreadyImported = [];
$players = Players::whereNotIn('id', $alreadyImported)
->get()
->random(25)
->pluck('id');
$groups = $players->map(function ($item, $key) use ($alreadyImported) {
array_merge($alreadyImported, $item->id);
$group = [
'username' => $item['username'],
];
return $group;
});
// $groups is a pivot table with group and players
Why does my $globalList always start at []? How can I carry the already-merged $globalList to the next map iteration?
The player IDs does not matter. It's for show. I am looking to pass the array through the map iterations.
Just use pluck() to get IDs from the collection:
$ids = $players->pluck('id');
Or, if you just need IDs:
$ids = Players::where('banned', false)->pluck('id');
If you're going to add any other data, you don't need to merge it to some array or a collection because map() will create a new collection.
Finally, you don't need to use collect() because get() will return collection.
I want to skip, some element from collection
$post_one = Post_one::all();
$post_two = Post_two::all();
$posts = collect();
if($post_one){
foreach($post_one as $post){
$posts->push($post);
}
}
if($post_two){
foreach($post_two as $post){
$posts->push($post);
}
}
//now i want to skip n=3, element form the collection of posts
$posts = $posts->sortBy('created_at')-<skip(3)->take(3);//does not work
error::Method skip does not exist.
To combine both records you can use merge method with flatten, i,e
$posts = $post_one->flatten(1)->merge($post_two)->sortBy('created_at');
Then you use filter to get the right result:
$filtered = $posts->filter(function ($post, $key) {
return $key > 2;
});
This skips the first 3 since the key starts from 0...n.
Or you can just slice the collection:
$nextthree = $posts->slice(3, 3);
This skips 3 and takes the next 3 from the collection. You can access the original collections $posts.
At this point the index of the collection is preserved, but to reset it to start from 0...n just use values() method i.e:
$nextthree = $posts->slice(3, 3)->values();
You can do it with forPage() method.
Like this:
$posts = $posts->forPage($currentPage, $perPage);
Documentation
Here is my code$titles = DB::table('roles')->lists('title');
How Can I cast $titles from a Laravel 5 collection into an associative array?
Include the ID in the function, and call from the Model:
$titles = Role::lists('title', 'id')->toArray();
Or call directly as you are doing:
$titles = DB::table('roles')->lists('title', 'id');
In this case, in an select field for example, the id will be the option value.
A laravel collection has a toArray method that will return a numerically keyed array of the contents. (The indexes will be keyed exactly as they are in the collection. To reset them call values on the collection first.)
$titles = DB::table('roles')->lists('title');
$result = $titles->toArray();
For an associative array you will need to do this manually using something like this.
$titles = DB::table('roles')->lists('title', 'id');
$result = [];
foreach($titles as $title) {
// using an ID as the key and title as the value
$result[$title->id] = $title->title;
}