I am having trouble showing user profile information in a profile page from the database which gives me Property [name] does not exist on this collection instance. (View: C:\xampp\htdocs\project_one\resources\views\profile.blade.php)
I have attached my code below
Route
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all()
]);
});
Profile Table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('address')->nullable();
$table->string('phone')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->timestamps();
});
}
Profile Model
class Profile extends Model
{
use HasFactory;
public function user(){
return $this->belongTo(User::class);
}
}
Function in User Model
public function profile(){
return $this->hasOne(Profile::class);
}
Blade template
<div >
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
CodePudding user response:
your user query "user" => User::all() you are passing to the profile page is the whole users in you DB which is a collection of many users you can't get a specific user name with that......if you want the name of the currently logged in user you will have to use
<div >
<label for="floatingName">Name</label>
<p>{{ auth()->user()->name }}</p>
</div>
without passing the user collection from your route.
or you can also pass the user logged in user through your route with this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(),
]);
});
and in your view
<div >
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
CodePudding user response:
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => User::all() // HERE IS THE PROBLEM
]);
});
User:all() returns collection of all users from the Database, For your case to get specific user on session use auth()->user()
Your Route should look like this
Route::get('/profile', function() {
return view('profile', [
"title" => "Profile",
"profile" => Profile::all(),
"user" => auth()->user(), // HERE IS THE SOLUTION
]);
});
Then you can use variable $user in a blade and get name of specific user
<div >
<label for="floatingName">Name</label>
<p>{{ $user->name }}</p>
</div>
