Search code examples
laravelforeign-keysposts

Laravel 'many to many' user associates with many posts?


In PostsController

public function store()
    {
        $this->validate(request(), [
            'title' => 'required',
            'body' => 'required'
        ]);

        auth()->user()->publish(
            new Post(request(['title', 'body']))
        );

        return redirect('/');
    }

in user.php

 public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public function publish(Post $post)
    {
        $this->posts()->save($post);
    }

the thing is after login I am seeing the all posts associate with only logged in user but i want many posts to many user relation


Solution

  • The user model must be like this

    class User extends Authenticatable
    {
           public function Posts()
           {
               return $this->belongsToMany('App\Post');
           }
    }
    

    The post model must be like this.

    class Post extends Model
    {
    
            public function users()
            {
                return $this->belongsToMany('App\User');
            }
    }
    

    The migration class for user

    class CreateUsersTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        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();
                  });
        }
    
       /**
            * Reverse the migrations.
            *
            * @return void
            */
           public function down()
           {
               Schema::dropIfExists('users');
           }
    }
    

    The migration class for Post

    class CreatePostsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
             Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->text('body');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('posts');
        }
    }
    

    Also u need a pivot table. The table name must be - user_post

    class CreatePostUser extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         * user_post
         */
        public function up()
        {
            Schema::create('post_user', function(Blueprint $table)
            {
                      $table->integer('user_id')->unsigned()->nullable();
                                $table->foreign('user_id')->references('id')
                                    ->on('users')->onDelete('cascade');
    
                                $table->integer('post_id')->unsigned()->nullable();
                                $table->foreign('post_id')->references('id')
                                    ->on('posts')->onDelete('cascade');
    
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('user_post');
        }
    }
    

    Please refer this link for more details - https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

    I hope you find this useful!