Laravel: Get pivot data for specific many to many relation - laravel

My User model has many Target and vice versa.
Now I've got a given User and given Target and I want to access pivot data from their relation. The pivot column is called type
How can I achieve this?

On the relationships for both User and Target, tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type.
If you're not iterating over a collection, but have a user and one of their targets and want the type field, you could use $target = $user->targets->find($targetId) and access the type with $target->pivot->type.
More at http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

Laravel 8.x
After accessing the relationship, you can access the intermediate table using the pivot attribute on your models
foreach ($user->targets as $target) {
echo $target->pivot->created_at;
}
Docs: https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

You can also limit columns by passing array as 2nd arg to simplePaginate
$query->users()->simplePaginate($per_page, ['users.id', 'users.email']);

Related

Laravel 6 check if a json field contains a value in a collection

I am trying to see if a user id is contained in a json field in my laravel collection. In my postgresql database I have a user_id field which contains a list of integers that pertain to my user model and table. I am aware in eloquent I can use the whereJsonContains method but I am not finding an equivalent method for a collection. How can I go about searching this user_id column for a specific user id?
check the manual for the aviable methods list:
https://laravel.com/docs/8.x/collections#available-methods
In your case i guess that is about:
where

How to fetch specified attributes from $this->belongsTo() in Laravel Eloquent?

I want to fetch some particular field from table rather than complete attributes in $this->belongsTo(); I can't use select('field_name') or pluck('field_name') or DB::raw(count(),avg()) etc with belongsTo,hasTo() .....
How i solve this problem?
I can't use
$this->belongsTo()->select('fiel_name')
or
$this->belongsTo()->pluck('fiel_name')
Please check the reference : How to join three table by laravel eloquent model
In the above reference, They fetched all attributes in blengsTo(), But in my case i have to fetch only particular attributes.
You have to use it like this
$this->belongsTo('Model')->select(array('field_name'));
where Model can be for example User etc.

Eloquent model setRelation generating array instead of Collection

If you are doing $instance = $model->with('categories')->find($id); and after var_dump($instance->categories) it going to return Collection of categories.
But on the project I'm working on in some heavy queries, we are not using with and getting data with a combination of GROUP_CONCAT and CONCAT, like this:
\DB::raw('GROUP_CONCAT(DISTINCT CONCAT(categories.id, ",,", categories.name) SEPARATOR ";;") as categories'),
And then we are building relations manually parsing result and creating a relationship using $instance->setRelation($relation, $data) but for some reason, it's returning an array of objects instead of Collection.
There are also option to use setRelations() and this method returning Collection but I found if you have bidirectional relations it's creating recursion and working really slow. For example: if in User model we have set $this->hasMany('Comments') and in Comments model we have set return $this->belongsTo('User'); and after when we running setRelations() to manually build relations it is create nesting models with recursion (User->Comments->User and so on).
The third option is to not use setRelation() or setRelations() and just to manually create Collection, populating it and set to model. But in such case, it will not be set as a model relation.
Any suggestions on how to build manually in the right way (to create relation is same way eloquent creating with with).
Group return collection of collection so you have to remove the keys of first collection and for that you can use values function of collection like this
$instance->setRelation('relation', $data->values()->all());
Details https://laravel.com/docs/5.6/collections#method-values

Laravel Eloquent: Access relationship of Original

In Laravel you can use getOriginal() on a model in order to get the original model (before changes since it was queried).
Now I need to access the relationship of that original model... is there a way to do that?
$item = OrderItem::where('id', $id)->with('qualification')->first();
$original_item = $item->getOriginal();
$original_item["qualification"] is not defined. I can access qualification_id though.
getOriginal() method returns array of the model's original attribute values, it is not a model itself, therefore you can not get a relationship.
So you can access the relationship using standard way: $item->qualification, that should not be affected by your changes of the parent model.

Laravel Eloquent : two keys relationship

I have a first table named "Building", and this one gets a Type and a Level. There are multiple building with same type and level.
I have another table named "BuildingInfo", who also gets a Type and a Level. The couple Type/Level is unique on this table.
Is there a way to have a HasOne relationship on Building, giving me the matching BuildingInfo ? The problem being that there are two keys on each table to get it, and I can only specify one key for each table with HasOne().
Thank you.

Resources