【问题标题】:Unable to Save to database using Laravel Api无法使用 Laravel Api 保存到数据库
【发布时间】: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();
}

在我的名为 categoryuserpivot 表中,我有这个表架构

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


【解决方案1】:

如果要传递用户 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]);
}

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 1970-01-01
    • 2020-01-15
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多