So i have 3 models: User, Team, Project
User ManyToMany Team.
Team ManyToMany Project.
I need to Retrieve the data from all project, based on the current user and his corresponding teams.
i tried writing it as a oneLiner:
$user->teams->projects
Error: Property [projects] does not exist on this collection instance.
but that didn't work. Is it possible as a oneliner or does it need to be used in a foreach loop
Solved By using this nested Foreach Loop:
$user = auth()->guard('api')->user();
if (!$user->hasRole(['directie', 'administrator'])) {
$collection = collect();
foreach ($user->teams as $team) {
foreach ($team->projects()->with('customer')->get() as $project) {
$collection->push($project);
}
}
$unique = $collection->unique('id');
return new ProjectCollection($unique);
}
return new ProjectCollection(Project::with("customer")->paginate(13));
Related
I made a Laravel project where Category, Subcategory and Child category working using same table relation.
I want to show all products from childcategory when click to Main Category.
So for that I need to use multiple foreach loop like this,
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
$products = $childcat->products;
}
}
Now I want to send $products to a view. How can I do it.
I don't want to use array. How can I send It. Please help.
Use Array()
$products = array()
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
$products[] = $childcat->products;
}
}
return view(....);
In Laravel you can pass your Category Object to the view. In Blade you have access to the relationships of Category. You can testet by :
dd($categories->subcategories) or dd($categories->subcategories[]->childcat).
I am trying to build an array of user ids from a long eloquent relationship, using nested foreach loops in a Laravel controller, but can't get it to work.
Users can have publishers, those publishers can have teams and each team has members. Users can be in multiple teams so I also need to remove duplicate IDs.
I want to end up with a count to see how many team members are associated with a user.
In my user model
public function publishers()
{
return $this->belongsToMany('App\Publisher')->withTimestamps();
}
In my publisher model
public function teams()
{
return $this->belongsToMany('App\Team')->withTimestamps();
}
and in my team model
public function members()
{
return $this->belongsToMany('App\User')->withPivot('status', 'title', 'team_role_ids')->withTimestamps();
}
and in my profile controller
foreach ($user->publishers as $userPublisher) {
foreach ($userPublisher->teams as $publisherTeam) {
$teamUserIds[] = $publisherTeam->members->pluck('id')->toarray();
}
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);
But I'm getting multiple arrays and not just one compiled array and the count isn't working. Any idea what I'm doing wrong?
You are assigning a new array into $teamUserIds each iteration. That's why you are getting multiple arrays.
$teamUserIds = [];
foreach ($user->publishers as $userPublisher) {
foreach ($userPublisher->teams as $publisherTeam) {
$teamUserIds = array_merge($teamUserIds, $publisherTeam->members->pluck('id')->toarray());
}
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);
you are adding arrays of id $publisherTeam->members->pluck('id')->toarray(); as a new index in $teamUserIds . but what you want to do is to merge the array of ids
so your code would be like this :
foreach ($user->publishers as $userPublisher) {
foreach ($userPublisher->teams as $publisherTeam) {
$teamUserIds = array_merge($teamUserIds , $publisherTeam->members->pluck('id')->toarray());
}
}
$deDupedIds = array_unique($teamUserIds, SORT_NUMERIC);
$idsCount = count($deDupedIds);
I am new to Laravel so I am confused how to do this
I have a table called groups where I forget to use unique in validation . After Long time I found out there are multiple datas with same name for ex :
I have two datas with same name called Feminism but with different id
The group table have only name and description columns , but it has relation with products many to many I have other datas too which has same name I want to merge those datas into one . along with the relation to the product . Is is possible ?
Shall I have to check all the names manually like
Item::where('name','Feminism')->get();
and then merge those datas or we have some other relavant methods
You can refactor this code for your models and relations
foreach ($groups as $group) {
$duplicates = Group::where('name', $group->name)->where('id', '<>', $group->id)->get();
foreach ($duplicates as $duplicate) {
$mustBeUpdatedRelation = $duplicate->products;
$anotherRelation = $duplicate->anotherRelation;
foreach ($mustBeUpdatedRelation as $product) {
$product->categories()->detach($duplicate->id); // if product has pivot data you must get these and assign to new relation
//new relation
$product->categories()->attach($group->id);
}
$anotherRelation = $duplicate->anotherRelation;
foreach ($anotherRelation as $item) {
// like above
// detach duplicated
// attach unique
}
//finally you can delete or .... duplicated group
$duplicate->update([
'name' => "duplicated_$duplicate->name"
]);
}
}
You may use the following
$items = App\Item::with('products')->get();
$tempArr = [];
foreach ($items as $key => $item) {
if(isset($tempArr[$item->name])) {
$merged = $tempArr[$item->name]['products']->merge($item->products);
unset($tempArr[$item->name]['products']);
$tempArr[$item->name]['products'] = $merged;
} else {
$tempArr[$item->name] = $item;
}
}
foreach ($tempArr as $item) {
$item->products()->sync($item->products->pluck('id'));
}
$idsToKeep = array_column($tempArr, 'id');
App\Item::whereNotIn('id', $idsToKeep )->delete();
Use onDelete cascade when defining your pivot table migration.
This takes care of deleting the model’s relations for you:
e.g.
$table->foreign(’item_id’)
->references(’id’)->on(’items’)
->onDelete(’cascade’);
Several models in yii2 are bound to a database using ActiveRecords. I now want to have a list of all ids of this model. Say, all user IDs when the Model is called User.
Sure I could just fetch all models and iterate over them, much like
$ids = [];
$users = User::find()->all();
foreach ($users as $user) {
$ids[] = $user->id;
}
But I feel there should be an easier way... Thanks in advance.
If you want to stay in ActiveRecord then this accomplishes the same thing:
$ids = User::find()->select('id')->column();
This returns array:
$ids = (new \yii\db\Query)->select('id')->from(User::tableName())->all();
Laravel 4
Is there any easy way to get all related models in one collection (only with Eloquent)?
For example, I want to get all of the students, that is related to many classes:
First, I need to get a collection with the relations:
$classes = Class::with('students')->whereIn('code', ['A', 'B'])->get();
Then I need to go through the entire collection to merge the students:
$allStudents = new Collection;
foreach ($classes as $class) {
$allStudents = $allStudents->merge($class->students);
}
Or if I need only one key, for example, id of the student, I'm doing this:
$allStudentsIds = [];
foreach ($classes->fetch('students') as $studentsArray) {
$allStudentsIds = array_merge(
$allStudentsIds, array_pluck($studentsArray, 'id')
);
}
Is there a method to get only related models? Or somehow I can make it through a request to the Student model?
Query based on students and join with classes?
Student::select('student.*')
->join('class_student', 'class_student.student_id', '=', 'student.id')
->join('class', 'class.id', '=', 'class_student.class_id')
->whereIn('class.id', $classes)
->get();
Something like that.
I assumed it is a many to many relationship and class_student is the association table