2017-03-03 54 views
0

在Laravel 5.4.1使用AJAX調用一個成員函數addvoter()上的空

FatalThrowableError在avController.php線53時,我總是收到此錯誤null

但它似乎沒有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

我想你「用戶」未設置,因爲您正在使用沒有CSR的ajax呼叫F保護?無論如何,這個問題似乎與用戶爲空的事實有關。 – Amarnasan

回答

0

如果用戶已登錄,我想你可以這樣做:

auth()->user()->addvoter()->save($voter); 
相關問題