On Laravel 5.4.1 I'm always getting this error when using ajax
FatalThrowableError in avController.php line 53: Call to a member function addvoter() on null
but it seems to work perfectly without ajax. I think the problem starts from $request->user()->addvoter()->save($voter);
which is my line 53 but I don't understand it;
/**
* 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']);
}
my user model
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');
}
my voter model
protected $fillable = ['FirstName', 'LastName', 'Email',
'Gender', 'StudentID', 'Level', 'Course',
'Stream', 'Nationality', 'ProfileImg' ];
public function user(){
return $this->belongsTo('elpebi\User');
}
via bil mason