2017-06-01 55 views
-1

我有控制器store()方法,它從表單獲取數據並將它們傳遞給用戶模型,方法名爲publish(),該方法在博客上發佈帖子。我的問題是,當我得到圖像文件的位置,我無法將其傳遞到存儲在用戶模型上的發佈方法。我曾嘗試通過像var請求,谷歌搜索,但沒有運氣。如何將圖像位置從控制器傳遞到模型方法以存儲數據庫Laravel

Store()方法:

public function store(Request $request){ 

     $this->validate($request, [ 

      'title' =>'required|max:48', 
      'body'=>'required', 
      'image'=>'required' 
     ]); 

     $post = new Post; 

     $destination ='uploads'; 
     $image = $request->file('image'); 
     $filename = $image->getClientOriginalName(); 
     $image->move($destination, $filename); 
     $location=$destination.'/'.$filename; 

     auth()->user()->publish(
      new post(request(['title','body', $location])) 
     ); 


     return redirect('/blog'); 
    } 
} 

和用戶模型發佈方法:

public function publish(Post $post){ 


    $this->post()->save($post); 

} 

爲了更清楚我想要的變量$位置插入它在新的崗位方法,因此可以得到發佈方法。

回答

1

確保在創建帖子時傳遞正確的數組鍵和值。由於您在數組中包含$location,它將從$location密鑰獲取請求數據。

這意味着$location的值就像'/path/to/image'。所以,基本上你是通過'/path/to/image'作爲關鍵。

嘗試修改如下。

auth()->user()->publish(
    new post([ 
     'title' => $request->title, 
     'body' => $request->body, 
     'location' => $location 
    ]) 
); 

另外,還要確保你已經在Post模型添加$fillable

相關問題