2016-07-15 91 views
0

我有兩個表格:用戶和帖子。我在這兩個表格之間建立了聯繫。當我嘗試保存時,由用戶創建的帖子發佈到表格。它不會傳遞用戶的ID。請檢查下面的代碼:無法獲取當前登錄用戶的ID

用戶模型(應用程序\ user.php的)

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Contracts\Auth\Authenticatable; 
class User extends Model implements Authenticatable 
{ 
    use \Illuminate\Auth\Authenticatable; 

    public function posts() 
    { 
     $this->hasMany('App\Post'); 
    } 
} 

郵政模型(應用程序\ post.php中)

<?php 

    namespace App; 

    use Illuminate\Database\Eloquent\Model; 

    class Post extends Model 
    { 
     public function user() 
     { 
      $this->belongsTo('App\User'); 
     } 
    } 

柱控制器( App \ Http \ Controllers \ PostController.php)

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Post; 
class PostController extends Controller 
{ 
    public function postCreatePost(Request $request) 
    { 
     //validation here will come 

     $post = new Post(); 
     $post->body = $request['body']; 
     $request->user()->posts()->save(); 
     return redirect()->route('dashboard'); 

    } 
} 

錯誤

Error

回答

0

我找到了解決辦法。所以,我會發布我的問題的答案。

我從Auth :: id()獲取當前登錄的user'id;

所以我改變了我的代碼如下

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Post; 
class PostController extends Controller 
{ 
    public function postCreatePost(Request $request) 
    { 
     //validation here will come 

     $post = new Post(); 
     $post->body = $request['body']; 
     $post->user_id = \Auth::id(); 
     $post->save(); 
     return redirect()->route('dashboard'); 

    } 
} 
+0

或'$請求 - >用戶() - > posts->保存($後)' – felipsmartins

+0

其實,我忘了補充雄辯關係之前的回報。這就是爲什麼我不能拔出或保存當前登錄的user'id。 –