Search code examples
laraveleloquentlaravel-8laravel-9

How to get the list of client related through the HasManyThrough relationship


I have these 3 tables:

clients

id - integer name - string

projects

id - integer client_id - integer name - string

tasks

id - integer project_id - integer name - string

related through the HasManyThrough relationship.

In the client table I have a column relating to the number of tasks relating to the projects of that specific client.

I want that when I click on the number of tasks, I am redirected to the view of the client related tasks. While when I click it shows me all the tasks, but I want, as already specified, the tasks related to the projects of that specific client.

How can I solve this problem?

VIEW:

<tr>
    <th class="id">ID</th>
    <th class="">Name</th>
    <th class="">Task</th>
</tr>
@foreach ($clients as $client)
<tr>
    <td>{{ $client->id }}</td>
    <td>{{ $client->name }}</td>
    <td>
        <a href="{{route('task.index'}" class="link-primary">{{ 
      $client->tasks_count }}
        </a>
    </td>
@endforeach

TaskController:

public function index()
{
    $tasks = Task::all();
    //dd($tasks);
    return view('task.index', compact('tasks'));
}

Solution

  • Create new route:

    Route::get('/client/{client}/tasks', ['as' => 'client.tasks', 'uses' => 'ClientController@tasks'])->name('client.tasks');
    

    Add something like this to your view:

    //Not sure if that is a right syntax to bind the id in the route, need to verify 
    <a href="{{ route('client.tasks', [$client->id]) }}" class="link-primary">
        {{ $client->tasks_count }}
    </a>
    

    Or:

    //Route
    Route::get('/client/{client}/tasks', [ClientController::class, 'tasks'])->name('client.tasks');
    
    //and view
    <a href="{{ URL::to('/client/' . $client->id . '/tasks') }}" class="link-primary">
         {{ $client->tasks_count }}
    </a>
    

    And controller:

    public function tasks(Client $client)
    {
        $tasks = $client->tasks;
    
        //return your view with tasks associated with this client
    }