I am trying to show the users profile information who are logged in,I have two tables one is Message and other one is User, when user login it see his\her profile, but there is an error.
profile.blade:
<table class="table table-bordered">
<thead>
<tr>
<th>
Name
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
@foreach($users as $usr)
<tr>
<td>
{{$usr->name}}
</td>
<td>
{{$usr->email}}
</td>
</tr>
@endforeach
</tbody>
Controller:
public function GetUserInfo($id){
$user = DB::table('users')
->join('messages', 'messages.user_id', '=', 'users.id')
->where('users.id', '=', $id)
->get();
if($user->count()){
$user = $user->first();
return view('profile')->with('users',$user);
}
}
Model:
class Messages extends Model
{
protected $table = 'messages';
protected $fillable = [
'message','user_id'
];
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
In
if($user->count()){
$user = $user->first();
return view('profile')->with('users',$user);
}
first()
is called on queries, but $user
already exists as a Laravel collection by the time it enters the if statement. It should exist as an object or an array, and you can access it as such. Something like
if($user->count()){
$user = $user[0]; /*OR*/
$user = $user->0;
return view('profile')->with('users',$user);
}
I don't recall which is the right way off the top of my head. print_r($user)
before to see what it looks like.
When passing data to views this way, users
should be an array.
Change your controller like this:
public function GetUserInfo($id){
$user = DB::table('users')
->join('messages', 'messages.user_id', '=', 'users.id')
->where('users.id', '=', $id)
->get()->toArray();
if($user->count()){
$user = $user->first();
return view('profile')->with('users',$user);
}
}
And your profile blade view:
<table class="table table-bordered">
<thead>
<tr>
<th>
Name
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
@foreach($users as $usr)
<tr>
<td>
{{$usr['name']}}
</td>
<td>
{{$usr['email']}}
</td>
</tr>
@endforeach
</tbody>