Reputation: 2735
I have two table named users
and profiles
.In users
table its have a column named id
and in profiles
table its have a column named userID
.Now i want when users
table increasing id
then userID
automatic fill up respectively.
If anyone create profile then the userID
column auto fill up according to the login users
table id
.How can i do that?
User Model:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profileHave(){
return $this->hasOne('App\Profile','userID');
}
}
Profile Model:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["userID","firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function userHave(){
return $this->belongsTo('App\User','userID');
}
}
But when i add a profile with an user then in profiles
table userID
column is blank.But it should be fill up according to login id of the users
table.
By the way i am new in Laravel. Thanks.
Upvotes: 2
Views: 1317
Reputation: 774
Get the user id like this
$id = Auth::id();
and then assign this value to user property in profile like
$profile->userID = $id
Upvotes: 1
Reputation: 6319
When saving a profile, add a user to it with:
$profile->userHave = $user
A couple of things:
Your Profile
model does not need userID
to be fillable. This is filled by your relation so really shouldn't be fillable.
The relation is named a bit weirdly. It should really be the name of the attribute that you expect to use to fetch the relation. For instance, I would call the user relation in your profile just user
:
public function user()
{
return $this->belongsTo('App\User','userID');
}
With this, you would add a user to a profile with the following:
$profile->user = $user;
Lastly, think about whether you actually need a profile model.
All the attributes in your profile model are attributes of the user. If you plan on having a profile for every user, you have no reason to have a different model for a profile.
Upvotes: 0