As already described, I want to get the name of the client whose id corresponds to the client_id present in the projects table (where client_id is the foreign key).
Relationship defined in the Client model:
public function projects()
{
return $this->hasMany(Project::class);
}
Relationship defined in the model Project:
public function client()
{
return $this->belongsTo(Client::class);
}
ClientController:
public function index()
{
$clients = Client::withCount('projects')->withCount('tasks')->get();
return view('client.index', compact('clients'));
}
ProjectController:
public function index($id)
{
$projects = Project::where('client_id', $id) ->withCount('tasks')->get();
return view('project.index', compact('projects'));
}
In the project view of that client I want to see the following line:
"List of projects related to (client name)"
Anyone who can kindly help me?
CodePudding user response:
Try the following
ProjectController:
public function index($id)
{
$projects = Project::where('client_id', $id)
->withCount('tasks')
->with('client')
->get();
return view('project.index', compact('projects'));
}
The model should have a relationship client
in it.
Note - you may want to remove the compact
statement.
CodePudding user response:
You already have a client ID, so why do a search of projects based on a foreign key column? One of the advantages of a framework like Laravel is you don't need to think about column names like client_id
, you just think about relationships. In this case you want the client information, so get that model and then use load()
to get the relationship information.
Things get a bit complicated if you want the count of each project's tasks. You need to specify a closure as part of the call to load()
.
public function index($id)
{
$client = Client::findOrFail($id)
->load(['projects' => function ($q) {
$q->withCount('tasks');
}]);
return view('project.index', compact('client'));
}
Now in your blade you can do this:
<p>List of projects related to {{ $client->name }}</p>
@foreach ($client->projects as $project)
<div>{{ $project->name }} has {{ $project->tasks_count }} tasks</div>
@endforeach
You should also look into route model binding to avoid having to do the lookup of the client model manually. Once your route is properly specified, your controller method can look like this:
public function index(Client $client)
{
$client->load(['projects' => fn ($q) => $q->withCount('tasks')]);
return view('project.index', compact('client'));
}