【发布时间】:2020-04-04 05:35:41
【问题描述】:
我的 laravel 应用程序中有很多对多的关系设置
在我的User Model 中,我已经建立了我的关系
public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}
在我的“类别模型”中,我已经建立了我的关系
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
在我的名为 categoryuser 的 pivot 表中,我有这个表架构
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');
更新
它返回错误"message": "调用成员函数 categories() on null"
【问题讨论】:
-
你能在
$user = Auth::user();之后dd($user);吗?结果如何? -
它返回 Null
-
所以表示没有用户登录。
-
我正在使用邮递员进行测试。我在表单中传递了 user_id 和 category_id 进行测试。但我认为这就是错误的来源。谢谢。
标签: php laravel api laravel-api