Reputation: 115
I have two table, the first is accounts (User model) which is used for auth and the other is students (t_student model) which contains the students details such student id (S_ID)
I am trying to get the S_ID inside the controller in store function for the logged in user.
$application = new Application;
$application->A_ID= $request-> input('A_ID');
$application->S_ID= Auth()->User()->students()->S_ID;
$application->S_Justification= $request-> input('Justification');
$application->save();
return redirect('/Abstracts')->with ('success', 'application submitted' );
MY User model (accounts table)
class User extends Authenticatable{
protected $table = 'accounts';
protected $primaryKey = 'Account_ID';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email', 'password', 'Account_Type', 'name'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function abstracts(){
return $this ->hasMany('App\Project' , 'PI_ID');
}
public function academics(){
return $this ->hasOne('App\T_user', 'Account_ID');
}
public function students(){
return $this ->hasOne('App\t_student', 'Account_ID');
}}
my t_student model
class t_student extends Model{
protected $table = 't_student';
protected $primaryKey = 'S_ID';
public function account(){
return $this ->belongsTo('App\User', 'Account_ID');}
and I am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$S_ID
EDIT: The error I am getting is related to my controller
$application->S_ID= Auth()->User()->students()->S_ID;
and the reason is my relationship but I am not sure what is wrong about it
Upvotes: 0
Views: 1886
Reputation: 138
In User model u must added the foregnkey to second parameter in hasOne func so replace the Account_ID by S_ID for ex :
// in user model
public function students()
{
return $this ->hasOne('App\t_student', 'S_ID');
}
// in ur controller romove the parentheses of students propriety
Upvotes: 0
Reputation: 1212
You should modify it:
$application->S_ID= Auth()->User()->students->S_ID;
Upvotes: 2