Astinox
Astinox

Reputation: 154

PHP Laravel 5.5 receiving multiple relations

I have a short issue regarding relations in Laravel. I recently created a task management list, which listed all the todo lists for each user. Each user had his own todo list, and no one could watch it.

It had the following structure:

id (int)
user_id (int)
title (string)
description (text)
done (bool)
finished_until (datetime)
created_at (datetime)
updated_at (datetime)

I had a normal relation going on with

public function tasks()
{
  return $this->hasMany('App\Task');
}

This works all perfectly fine. Now I added the option of adding additional relations for the user. What I did was:

public function tasksRelated()
{
  return $this->belongsToMany('App\Task', 'task_relations', 'task_id');
}

This also worked fine. I was wondering if there is now a way to get ALL tasks at the same time related to the user (own and related ones)?

Upvotes: 1

Views: 45

Answers (1)

HPierce
HPierce

Reputation: 7409

$user->tasks and $users->tasksRelated will both be eloquent collections.

You can merge them via merge():

$ownTasks = $user->tasks;
$relatedTasks = $user->tasksRelated;
$allTasks = $ownTasks->merge($relatedTasks);

Upvotes: 1

Related Questions