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');
}
}
個
錯誤
或'$請求 - >用戶() - > posts->保存($後)' – felipsmartins
其實,我忘了補充雄辯關係之前的回報。這就是爲什麼我不能拔出或保存當前登錄的user'id。 –