Reputation: 157
i want to display the user's name in the post who post the project. but its showing ERROR : Trying to get property of non-object in view file.
i have user table and project table. in project table i have foreign key user_id. but i couldn't access the name of the user and even the user id from the user table. in project table the user_id is 0 and it is not same as in user table. how i should solve this?
user model:
public function project()
{
return $this->hasMany('App\Project');
}
project model:
public function User() {
return $this->belongsTo('App\User','user_id');
}
migration users table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
Migration project table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id')->unique();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('name');
$table->text('description');
$table->date('date');
$table->timestamps('date');
});
view file:
@foreach ($projects as $key => $project)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $project->name }}</td>
<td> {{$project->user_id->name}}</td>
<td>{{ $project->description }}</td>
<td>{{ $project->date }}</td>
Upvotes: 0
Views: 6322
Reputation: 26
1) correct small mistake form your table such as user_id and User_id
2) Let me solve first relationships:
One user can have many project. one project can belongs to one user.
Model class solve
class Project extend Modeletcc
{
public function projectusers() {
return $this->hasOne('App\Project', 'user_id', 'id);
}
}
then get data from controller such as
class ProjectController extends Controller {
// to get data
public function __contstruct() {
$this->project = Project::with('projectusers')->get();
}
// function for ending data to view
public function tesview() {
return view('view whic you wanna send your data',
[
'project_details' => $this->project
]);
}
then inside view you can simple get all data which you want
@foreach($project_details as $project) {
@foreach($project->projectusers as $users) {
{{ $user->name }}
}
}
Upvotes: 1
Reputation: 7420
You cant access user who posted the project through the project id. You need to reference the relationship and then call the model property. Like so:
@foreach ($projects as $project)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $project->name }}</td>
<td> {{$project->user->name}}</td>
<td>{{ $project->description }}</td>
<td>{{ $project->date }}</td>
@endforeach
Upvotes: 0