aegyed
aegyed

Reputation: 1330

Laravel Many to Many relation

I getting started with Eloquent, and I've ran into a problem. I trying to setup a many to many relation schema + model.

Here is the code:

routes.php snippet:
$user1 = User::findOrFail(1);
$user2 = User::where('username', '=', 'TestUser')->get();
// we make $user1 to follow $user2
$user1->followedBy()->save($user2);

User model snippet:

public function followedBy() {
    return $this->belongsToMany('User', 'user_follows', 'user_id', 'follow_id');
}

public function following() {
    return $this->belongsToMany('User', 'user_follows', 'follow_id', 'user_id' );
}

DB Schema snippet:

Schema::create('user_follows', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('follow_id');
            $table->timestamps();
        });

The error I get when I visit the routes:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in /Applications/MAMP/htdocs/Laravel/proj2/app/routes.php on line 84 and defined 

Upvotes: 0

Views: 861

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

The error says it all:

$user2 = User::where('username', '=', 'TestUser')->get();
// returns Collection

You need this instead:

$user2 = User::where('username', '=', 'TestUser')->first();
// returns single Model

And by the way:

// we make $user1 to follow $user2
$user1->followedBy()->save($user2);

it's $user2 to follow $user1 and use this:

$user1->followedBy()->attach($user2);

For save is saving the $user2 model first, what is redundant here. It's used in such cases:

$user2 = new User;
// assign some properties
...
$user1->followedBy()->save($user2);

Upvotes: 1

Related Questions