Php 无法使用Laravel Api保存到数据库
我的laravel应用程序中有多对多关系设置 在我的Php 无法使用Laravel Api保存到数据库,php,laravel,api,laravel-api,Php,Laravel,Api,Laravel Api,我的laravel应用程序中有多对多关系设置 在我的用户模型中,我已设置了关系 public function categories() { return $this->belongsToMany(Category::class)->withTimestamps(); } 在我的“分类模型”中,我建立了我的关系 public function users() { return $this->belongsToMany(User::class)->with
用户模型中
,我已设置了关系
public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}
在我的“分类模型”中,我建立了我的关系
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
在我的pivot
表categoryuser
中,我有这个表架构
public function up()
{
Schema::create('category_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
我正在尝试使用此方法将添加到数据透视表中进行保存
public function categoryUserapi (Request $request)
{
$validatedData = $request->validate([
'category_id' => 'required|array|min:3',
'category_id.*' => 'integer',
]);
$user = Auth::user();
$user->categories()->attach($request->input('category_id'));
return response(['user'=> $user]);
}
但它不起作用,我不知道我做错了什么
在我的api.php中,我有
Route::post('/onboardcategory', 'OnboardsController@categoryUserapi');
更新
它返回了错误
“消息”:“对空成员函数categories()的调用”
如果要传递用户id,请将Auth::user更改为user::find
public function categoryUserapi (Request $request)
{
$user = User::find($request->user_id);
$user->categories()->attach($request->input('category_id'));
return response(['user'=> $user]);
}
你能
dd($user)
在$user=Auth::user()之后代码>?结果是什么?它返回空值,这意味着没有用户登录。我正在使用postman进行测试。我在表单中传递要测试的用户id和类别id。但我认为这就是错误的来源。谢谢