我最近一直在研究CRUD系统,我想要的是当登录用户在我的网站上创建产品时,他的名字将自动作为外键插入我的产品表中。
这是我为其制作的产品型号。
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name
protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','users_id','created_at', 'updated_at'];
protected $table = "product";
这是我的ProductController商店功能
public function store(Request $request)
{
$product = Product::create($request->only(['naam', 'inkoopprijs', 'verkoopprijs', 'users_id']));
return redirect(route('product.index'));
}
答案 0 :(得分:2)
您可以使用Eloquent events执行此操作:
Product::creating(function ($product) {
$user = auth()->user();
$product->users_id = $user->id;
});
答案 1 :(得分:1)
您可以在表单中将用户ID用作隐藏字段,但需要考虑在表单中使用用户ID的安全性方面。这取决于您使用的位置。可能是你可以使用这种方法是用户已经过身份验证。
<input type="hidden" name="users_id" value="{{Auth::user()->id}}">
答案 2 :(得分:1)
您可以使用const portArray = [1,4];
return {
portArray.map(value =>
({ label: value value: value }))
};
});
或Auth::user();
我们还可以使用auth()->user();
Auth::id();
我希望这就是你的意思。