I have a relationship between a 'Project' and a 'Client'. Here are my models..
class Client extends Model
{
public function projects() {
return $this->hasMany('App\Models\Project');
}
}
class Project extends Model
{
public function clients() {
return $this->belongsTo('App\Models\Client');
}
}
In my 'Projects' controllers index method..
$projects = Project::all();
return view('project/projects', compact('projects'));
And then in my blade file..
@foreach($projects as $project)
<div class="project">
<div class="status pending"></div>
<p>{{ $project->name }}</p>
<span>{{ $project->clients->name }}</span>
</div>
@endforeach
I get the following error 'Trying to get property of non-object'. New to Laravel, please go easy.
That code sure looks like it would work (or wouldn't work but for a different reason), but I've found that sometimes you need to do something like this for relationships to work like you might expect:
$projects = Project::with('clients')->get();
return view('project/projects', compact('projects'));
Also note that since clients
is a HasMany relationship, you'll need to iterate over $projects->clients
to get at the ->name
attribute of one of them.
In my client_id column in my projects table, one of the fields was set to 0. So when iterating and getting to that point it failed and that is what my error message was pertaining to.