Search code examples
phplaravelapilaravel-api

Unable to Save to database using Laravel Api


I have a many to many relationship setups in my laravel application

In my User Model, I have setup my relationship

public function categories()
{
    return $this->belongsToMany(Category::class)->withTimestamps();
}

In my 'Category Model` I have set up my relationship

public function users()
{
    return $this->belongsToMany(User::class)->withTimestamps();
}

In my pivot table named categoryuser I have this table schema

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();
    });
}

I am trying to add to save to my pivot table with this method

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]);
}

But it's not working, I don't know what I am doing wrong

In my api.php, I have this

Route::post('/onboardcategory', 'OnboardsController@categoryUserapi');

UPDATE

It returned error

"message": "Call to a member function categories() on null"


Solution

  • Change Auth::user to User::find if you are passing user id

    public function categoryUserapi (Request $request)
    {
    
    
      $user = User::find($request->user_id);
      $user->categories()->attach($request->input('category_id'));
    
      return response(['user'=> $user]);
    }