繁体   English   中英

laravel为用户错误设置配置文件页面此集合实例上不存在属性[user]

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

我试图建立一个页面,用户可以在其中添加关于他自己的描述,例如,他或她所从事的兴趣是什么,因此我与用户建立了单独的表,因此有一个USER表和PROFILE表,两个表的外观

用户表

 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();
    });

资料表

 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();
    });
}

因此在矿山模型中,我为配置文件和用户建立了关系,在laravel和hasone()中使用belognsto()函数,该模型的外观

user.php的

public function profile()

{

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

}

profile.php

public function user()

{

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

}

但是当我尝试将其添加到刀片时出现错误

  {{ $profile->user }}

它说无法找到该变量,所以我没有在laravel中设置关系船,因为它给出了错误或者是其他东西

错误是[属性[用户]在此集合实例上不存在。]

ProfileController.php

public function index()

{
    $profile = Profile::all();

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

}

正如Vahe Shak所述,您的个人资料表需要一个外键来显示user_id与users表中的id相关。 您的个人资料表迁移需要具备以下条件:

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

但是,编辑迁移将无法有效地进行更改。 使用新的迁移

php artisan make:migration add_foreign_to_profile

然后,迁移应如下所示:

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'); 
    });
}

然后,您可以运行php artisan migration

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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