Getting an indexed collection - laravel

I would like to get an indexed collection from an eloquent call to get a specific item:
$items = FeedItem::all();
$specific_item = $items[4];
Or is it possible to do something like:
$items->get('id', 4);
where id is the attribute and 4 is the value of the attribute.

FeedItem::all() will return a Illuminate\Database\Eloquent\Collection.
To get a specific model you can use the find method:
$items = FeedItem::all();
$item = $items->find($id);
For more methods of the Collection class see the docs and the api.

Related

Laravel eloquent make visible only given attribute in one instance of model

i have instance model from
$model = Model::find(1);
for example this instance always return these attribute (some is from $append):
-id
-name
-countRelation
-description
-created_at
-updated_at
what i want is to only retrive name and description from this instance;
makeVisible only work to show hidden attribute; i don't want use makeHidden because the result of find may change if on model i add new append attribute;
Since you are appending accessors limiting the SELECT statement won't stop those from being appended to the serializied output. You can use setVisible to do this though:
$model->setVisible(['name', 'description']);
Setting what is visible this way will limit the attributes, appends and relationships that are returned in the serialized output of the Model.
You can use select to only retrieve some column in your database, it will not affect append, see the doc for more info Eloquent
$model = Model::find(1);
// to this
$model = Model::select('name', 'description')->find(1);
See Query Builder for more insight about grabbing data from database.
if you retrieve name and description only, then you may use
$model = Model::select(['name', 'description'])->find(1);
You can use select() to select only certain columns in your query.
$model = Model::select('name', 'description')->find(1);
https://laravel.com/docs/8.x/queries#specifying-a-select-clause
You can also get the Model and use functions on the model. If you have a single Model you can use get().
$model = Model::find(1)->get('name', 'description');
If you have a collection you can use ->map->only(). This maps the only function as a callback for each Model in your Collection.
$models = $models->map->only(['name', 'description']);

Laravel How to pass parameter to Accessor method in model via where condition while query building?

I have a Accessor method in Collection Model getSizesAttribute, which returns array of available sizes eg: ['S','L'], Now I need to get Models with have size 'S'. like:
$collections = $collections->where('sizes','S');
But sizes is array, could I manipulate this anyhow so that I could check returns only if sizes have specific size.
I tried making another method getIsSizeAttribute, like:
public function getIsSizeAttribute($size){
return in_array($size,$this->sizes);
}
Now How could I user this in Where condition like
$collections = $collections->where('is_size','S');
Mutators and Accessors only run skin-deep, after the query's already been executed. You could use Collection::filter() as Bangnokia suggests, but that wouldn't give you any performance benefit of actually applying the condition to the initial request.
I think what you're looking for here is a Query Scope. Add something like this to your Model class:
public function scopeSize(\Illuminate\Database\Eloquent\Builder $query, $size)
{
return $query->whereIn('sizes', $this->sizes[$size]);
}
And access it like this:
$collection = $model->size('S')->get();
You should use filter on collection
$collections = $collections->filter(function($item, $index) {
return in_array('S', $item->sizes);
});

Can't modifiy eloquent query result

So I got the following code in my controller's show function which just returns a page with the tags:
$page = Post::with('tags')->findOrFail($id);
$page->tags->lists('name');
return response($page);
When I try to to execute this, it won't change the tags key, which is an array with the tags from the eloquent belongsToMany relationship.
Why isn't this working? To me it seems pretty handy to just change a value like this.
When I change it to $page->test = $page->tags->lists('name') it will add the test key as usual.
How would I modify a eloquent value in a easy way?
What works pretty well for such cases is overriding toArray in your Model:
public function toArray(){
$array = parent::toArray();
$array['tags'] = $this->tags->lists('name');
return $array;
}
After the $page = Post::with('tags')->findOrFail($id); line is executed, $page->tags is going to be an Illuminate\Database\Eloquent\Collection object containing all the related Tags for the Post. From your provided code and question, it sounds like you want to then change $page->tags to be an array containing just the related tag names.
The statement $page->tags->lists('name') is only going to return an array of all the names of the related tags; it does not modify the underlying collection. If you wanted to modify the $page->tags attribute, you would need to assign it the result of your statement:
$page->tags = $page->tags->lists('name');
However, $page->tags was an attribute that was dynamically created and assigned by the Model, and is expected to hold the contents of a relationship. Manually modifying the contents like this may have unintended consequences, but I do not know.
Edit
The Model::toArray() method merges in the relationship information over the attribute information. So, you can change the attribute, but if you echo the model, the relationship information will show up over your attribute change.
$page->tags = $page->tags->lists('name');
// this will echo the tags attribute, which is now the array of tags
echo print_r($page->tags, true);
// this will echo the model, with the tags attribute being
// overwritten with the related data
echo $page;
One option would be to unset the attribute (which also unsets the relationship) and then reassign the attribute to your desired data:
$page = Post::with('tags')->findOrFail($id);
$temp = $page->tags;
unset($page->tags); // you must unset the attribute before reassigning it
$page->tags = $temp->lists('name');
return response($page);
A little bit cleaner would be to use a different attribute name:
$page = Post::with('tags')->findOrFail($id);
$page->tagNames = $page->tags->lists('name');
unset($page->tags);
return response($page);
And another option is to do what #lukasgeiter suggested and override the Model::toArray method:
class Post extends Model {
public function toArray() {
// call the parent functionality first
$array = parent::toArray();
if (isset($this->tags)) {
$array['tags'] = $this->tags->lists('name');
}
return $array;
}
}
If you want to change the output of one of the relationships in the toArray/toJson methods, then use accessor:
// in order to not show the underlying collection:
protected $hidden = ['tags'];
// in order to append accessor to toArray output
protected $appends = ['allTags'];
// mutate the collection to be just an array of tag names
public function getAllTagsAttribute()
{
$collection = return $this->getRelation('tags');
return ($relation) ? $collection->lists('name') : [];
}
then you will get simple array instead of collection when you do $page->allTags or in the toArray/toJson output, while not showing the real collection.
It is allTags not `tags, since the latter should remain eloquent dynamic property, so you can work with it as usual before outputting anything.
not sure if this helps. To be honest, I do not get your point. But I guess there is something wrong with this line:
$page->tags->lists('name');
If $page->tags is a belongsToMany relationship and you want to add more query conditions after this relationship, you should query like this:
$page->tags()->lists('name');

laravel access model properties

I am looking for solution how to access eloquent model items by 'alias' field.
There is no problem accessing items by 'id'. But building a custom query I find myself unable to access item properties.
This piece of code works perfect
$cat = Category::find(1);
return $cat->title;
But if I am querying items with any other argument - properties are inaccessible
This code
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;
throws an exception
Undefined property: Illuminate\Database\Eloquent\Collection::$title
Could you please help.
You already got the answer but here are some insights, when you use get() or all(), it returns a collection of model objects, which is an instance of Illuminate\Database\Eloquent\Collection, so here you'll get a Collection object
$cat = Category::where('alias','=','vodosnab')->get();
Now, you can use, $cat->first() to get the first item (Category Model) from the collection and you may also use $cat->last() to get the last item or $cat->get(1) to get the second item from the collection. These methods are available in the Collection object.
Using the first() method like Category::where('alias','=','vodosnab')->first(); will return you only a single (the first mathing item) model which is an instance of your Category model. So, use all() or get() to get a collection of model objects and you can loop through the collection like:
foreach(Category::all() as $cat) { // or Category::get()
$cat->propertyName;
}
Or you may use:
$categories = Category::where('alias','=','vodosnab')->get();
foreach($categories as $category) {
$category->propertyName;
}
Also, you may use:
$categories = Category::where('alias','=','vodosnab')->get();
$firstModel = $categories->first();
$lastModel = $categories->last();
$thirdModel = $categories->get(2); // 0 is first
If you need to get only one then you may directly use:
$category = Category::where('alias','=','vodosnab')->first();
$category->fieldname;
Remember that, if you use get() you'll get a collection of Model objects even if there is only one record available in the database. So, in your example here:
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;
You are trying to get a property from the Collection object and if you want you may use:
$cat = Category::where('alias','=','vodosnab')->get();
return $cat->first()->title; // first item/Category model's title
return $cat->last()->title; // last item/Category model's title
return $cat->get(0)->title; // first item/Category model's title
You may read this article written on Laravel's Collection object.
get() returns a Collection of items. You probably need first() that returns a single item.

Doctrine Query Builder - How to select a many-to-many relationship?

I have a form in Symfony2 that needs to have an entity choice field filled with a collection of Players in a particular tournament. I create the form Type and pass the tournament ID to the query_builder property of the correct field. In the entity repository I have this method:
public function allPlayersInTournamentQuery($tournament_id)
{
$repo = $this->getEntityManager()->getRepository('GameBundle:Tournament');
$tournament = $repo->find($tournament_id);
$players = $tournament->getPlayers();
$playersIds = array();
foreach ($players as $player) {
$playersIds[] = $player->getId();
}
$playersQuery = $this->createQueryBuilder('p')
->in('p.id', $playersIds)
->orderBy('p.real_name', 'ASC');
return $playersQuery;
}
The function in() does not exist in the query builder. I hope the method shows what I am trying to do. Im tying to return the query builder that selects the correct players found in the given tournament.
How can I achieve this?
Thanks!
You can use the helper methods provided by the query builder $playersQuery->expr()->in('p.id', $playersIds)
Your query will be something like that:
$playersQuery = $this->createQueryBuilder('p');
$playersQuery->where($playersQuery->expr()->in('p.id', $playersIds))
->orderBy('p.real_name', 'ASC');
More information about the helper methods here

Resources