简体   繁体   中英

laravel setting up an profile page for the users error Property [user] does not exist on this collection instance

Im trying to set up a page where an user can add a description about him self for example what kind of hobbies he or she is interrested in so i made a sepperate table from the users, so theres an USER table and a PROFILE table this is how both tables looks

user table

 public function up()
 {
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

profile table

 public function up()
 {
    Schema::create('profiles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->string('email')->unique();
        $table->string('firstname');
        $table->string('lastname');
        $table->integer('age');
        $table->integer('birthdate');
        $table->text('bio');
        $table->timestamps();
    });
}

so whit in mine models i set a relationship to the profile and user whit belognsto() function in laravel and hasone() this how the model looks

user.php

public function profile()

{

    return $this->hasOne(Profile::class);

}

profile.php

public function user()

{

    return $this->belongsTo(User::class);

}

but I get an error when I trying adding this to the blade for example

  {{ $profile->user }}

its says the variable is unable to be found, so did I not set the relation ships right in laravel that its giving the error or is it someting else

the error is [Property [user] does not exist on this collection instance.]

ProfileController.php

public function index()

{
    $profile = Profile::all();

    return view ('profile.show',compact('profile'));

}

Just as Vahe Shak already mentioned, your profile table needs a foreign key to show user_id is related to id in the users table. Your profile table migration needed to have:

$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

But editing the migration would not effectively make the changes. Use a new migration

php artisan make:migration add_foreign_to_profile

Then the migration should be looking like this:

public function up()
{
    Schema::table('profiles', function(Blueprint $table)
    {
         $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

public function down()
{
    Schema::table('profiles', function(Blueprint $table)
    {
        $table->dropForeign('user_id'); 
    });
}

Then you can run php artisan migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM