Search code examples
databaselaraveldatabase-connectionlaravel-facade

How to connect 'users' table with 'post' table in laravel?


This is my structure, I want to connect these two tables in laravel, How to do it?

Post Table:

public function up()
{
    Schema::create('post', function (Blueprint $table) {
        $table->increments('post_id');
        $table->string('post');
        $table->integer('time');
        $table->string('host');
        $table->integer('vote_up');
        $table->integer('vote_down');
        $table->foreign('id_fk')->references('id')->on('users');
        $table->timestamps();
    });
}

Users Table:

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

Solution

  • I presume you are just pasting in migrations but you do need to have yours users table created before your posts table. I would change

    $table->foreign('id_fk')->references('id')->on('users');
    

    to

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

    Because Laravel can infer foreign keys:

    Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Post model is not user_id, you may pass a custom key name as the second argument to the belongsTo method

    And then all you need in your models is the following:

    class Post extends Model
    {
        /**
         * Get the user that owns the post.
         */
        public function user()
        {
            return $this->belongsTo('App\User');
            // if you want to keep your current structure:
            // return $this->belongsTo('App\User', 'id_fk', 'id);
        }
    }
    

    and

    class User extends Model
    {
        /**
         * Get the post for a user.
         */
        public function posts()
        {
            return $this->hasMany('App\Post');
            // if you want to keep your current structure:
            // return $this->belongsTo('App\Post', 'id_fk');
        }
    }
    

    You can read more about setting up relationships here.