Search code examples
laravellaravel-5eloquentlaravel-bladelaravel-5.3

Loop through nested relation in view


I'm trying to loop through some data in my blade view. This is my database setup:

enter image description here

What I would like to have in my view is the following:

enter image description here

So I can loop through the days and then order the tasks by the category they are in. I'm not experienced with Laravel and I'm having difficulties on ordering the tasks by category in the best way.

In my Days Model I have:

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

In my Task Model I have:

public function days()
{
    return $this->belongsToMany('App\Day');
}

public function category()
{
    return $this->belongsTo('App\Category');
}

In my Category Model I have:

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

In my controller I now only have:

public function index()
{
    $categories = Category::all();

    return view('app.blade.php', compact('categories'));
}

But how can I make sure to order them by days and then by category? Help much appreciated.


Solution

  • You can try as following:

    $days = Days::with('tasks.category')->get();
    
    $days = $days->map(function ($day) {
        $day->tasks = $day->tasks->groupBy('category_id');
    
        return $day;
    });
    

    Check it how it is converted after groupBy() method

    dd($days);
    

    then in your view you can do as:

    @foreach ($days as $day)
        {{ $day->name }}
        @foreach ($days->tasks as $tasks)
            {{ $tasks->first()->category->name }}
            @foreach ($tasks as $task)
                {{ $task->name }}
            @endforeach
        @endforeach
    @endforeach
    

    Note - I have not tested it but you can give it a try.