0

I have a table tasks and users that have tasks_ids from the tasks table. I would like to show only the tasks data that users have based on his tasks_ids. Please see illustration below.

tasks table

---------------
-- id | name --
-- 1  | task1 --
-- 2  | task2 --
-- 3  | task3 --
---------------

users table

----------------------------
-- id | name  | tasks_ids --
-- 1  | Ryan  | 1         --
-- 2  | Joe   | 1, 2      --
-- 3  | Mark  | 1, 2, 3   --
----------------------------

Below is my code but it only shows if user has only 1 task.

<table>
  <tr>
    <td>Task Name</td>
  </tr>
  @foreach($tasks as $task)
    @if($task->id == Auth::user()->tasks_id)
      <tr>
        <td>{{$task->name}}</td>
      </tr>
    @endif
  @endforeach
</table>

If I logged in as Joe the excepted output should be:

---------------
-- Task Name --
-- task1     --
-- task2     --
---------------
Ryan R
  • 13
  • 4
  • Show us your fetch query. – Abdulla Nilam Oct 03 '22 at 16:23
  • 1
    Actually, `user` table should be redesigned. `tasks_ids` should not exist. Have a tasktouser table. Then join the three tables together and you can pull all the tasks you require. Current implementation would be very inefficient as all tasks would need to be pulled for every load. See https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad if unfamiliar. – user3783243 Oct 03 '22 at 16:23
  • 1
    Performing queiries on `CSV` fields can be troublesome and generally recommended to avoid. Consider using something like a [`pivot table`](https://laraveldaily.com/post/pivot-tables-and-many-to-many-relationships) instead. – Peppermintology Oct 03 '22 at 16:34
  • 1
    Possibly `explode(',', Auth::user()->tasks_id)` and `in_array` but really should reconsider the whole process. – user3783243 Oct 03 '22 at 16:51
  • Agreed with all the comments above. `users.tasks_ids` column should be deleted, and the values in each should be moved to a `pivot_table`, like `task_user` (if going by Laravel's conventions), then you'd be able to define a [`belongsToMany()`](https://laravel.com/docs/9.x/eloquent-relationships#many-to-many) relationship between `User` and `Task`. You'd then be able to do `@foreach(auth()->user()->tasks as $task)`, or `Task Count: {{ auth()->user()->tasks->count() }}`, etc. This _can_ be done with your code, but not easily, and definitely not efficiently. – Tim Lewis Oct 03 '22 at 18:43
  • Thank you for all comments and suggestions. – Ryan R Oct 03 '22 at 23:43

0 Answers0