Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

The reason is a simple logic error on your part.

When you create a new tag, it only lives in memory until you save it. Hence the tag won't be assigned an id because it hasn't been saved. Once you save the new model the auto_increment on the id field will generate a new id and laravel will assign the id to the model.

The tag needs an id to attach the user to in the lookup table.

Try this:

$tag = New Tag;
$tag->name = $tagName;
var_dump($tag->id);

^^this will throw a error because tag has no id yet^^

Now this:

$tag = New Tag;
$tag->name = $tagName;
$tag->save();
var_dump($tag->id);

^^this will display the new id^^

So what you want is

$tag = New Tag;
$tag->name = $tagName;
//save tag to get a generate a tag id on the model
$tag->save();
$tag->users()->attach(Input::get('userID'));
Last updated 2 years ago.
0

Thanks for the help, I think I have it working!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.