Reputation: 91
i have a problem with reading out data with a relationship. some how it returns Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$id. I have no clue what i did wrong since i just started using laravel.
model 1 Project:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = "project";
public function projectitem()
{
return $this->hasMany('App\Projectitem');
}
}
model 2 Projectitem:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Projectitem extends Model
{
protected $table = "project_item";
function project(){
return $this->belongsTo('App\Project');
}
}
index.php
@foreach ($projects as $project)
<tr>
<td>{{$project->projectitem()->id}}</td>
<td></td>
</tr>
@endforeach
i have no clue why this happens, i've tried a couple of solutions but none seems to work.
Any help would be appreciated
Upvotes: 2
Views: 9803
Reputation: 5603
You have collection of Projects Object in the $projects
after you perform a loop you get each project as $project
depending on the state of the loop. When you call the projectitem
It will return a collection of ProjectItem
and not a single ProjectItem
that is the reason why $id
is undefined. You should form another loop to get each ProjectItem separatly
@foreach ($projects as $project)
// $project->projectitem() return a collection of projectitem
// and not a single projectitem
// to access ID of each projectitem you must perform another loop
@foreach ($project->projectitem() as $projectitem)
// here project id is disponible as property accessible like this
{{ $projectitem->id }}
@endforeach
@endforeach
Upvotes: 1
Reputation: 1092
Look at the relation - it is hasMany relation. meaning, on project has many project items.
try thhis,
@foreach ($projects as $project)
@foreach ($project->projectitem as $projectitem)
echo $projectitem->id
@endforeach
@endforeach
NOTE: this inner loop is necessary only if the relation is hasMany. if it is hasOne, no need to change anything in you loop, just change the relation to hasOne and run.
Upvotes: 3