在Laravel 5.4.1上,当使用ajax时,我总是遇到这个错误
avController.php第53行中的FatalThrowableError:在null上调用成员函数addvoter()
但是如果没有ajax它似乎完美无缺。我认为问题从$request->user()->addvoter()->save($voter);
开始,这是我的第53行,但我不明白;
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->isMethod('post')){
$voter = new voter();
$voter->FirstName = $request->fname;
$voter->LastName= $request->lname;
$voter->Email = $request->email;
$voter->PhoneNumber = $request->phone;
$voter->Gender = $request->optradio;
$voter->StudentID = $request->sID;
$voter->Level = $request->level;
$voter->Course = $request->course;
$voter->Stream = $request->stream;
$voter->Nationality = $request->nat;
$voter->ProfileImg = $request->image;
$request->user()->addvoter()->save($voter);
$response = array(
'fname' => $request->fname,
'lname' => $request->lname,
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
return response()->json(['response' => 'This is get method']);
}
我的用户模型
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function addcandidate(){
return $this->hasMany('elpebi\addcandidate');
}
public function addstcandidate(){
return $this->hasMany('elpebi\stcandidate');
}
public function addvoter(){
return $this->hasMany('elpebi\voter');
}
public function newelection(){
return $this->hasMany('elpebi\election');
}
我的选民模特
protected $fillable = ['FirstName', 'LastName', 'Email',
'Gender', 'StudentID', 'Level', 'Course',
'Stream', 'Nationality', 'ProfileImg' ];
public function user(){
return $this->belongsTo('elpebi\User');
}
答案 0 :(得分:0)
如果您的用户已登录,我认为您可以执行此操作:
auth()->user()->addvoter()->save($voter);