zahra_oveyedzade
zahra_oveyedzade

Reputation: 1220

using associate method in laravel

Assume we have one to many relationship like post and comment, each post hasMany comments and each comment belongsTo one post. The question is how we could call associate method? in Laravel document the associate method is called on relation method, something like:

$comment = new Comment(['title' => 'something']);    
$post->comments()->associate($comment);

but in some cases, I saw the associate method is called on relation attribute like:

$comment = new Comment(['title' => 'something']);    
$post->comments->associate($comment);

Are they the same? is there any difference between them?

Thanks

Upvotes: 0

Views: 656

Answers (1)

Dan
Dan

Reputation: 5358

I don't think calling associate on a loaded relationship property works as it's either a database collection or a model (depends on the type of the relation). The method associate is only available on BelongsTo and MorphTo relationships.

Upvotes: 2

Related Questions