Home > OS >  Laravel not fills pivot table in API nested call
Laravel not fills pivot table in API nested call

Time:08-24

I'm a beginner in Laravel. I try to create API with nested resources, so: I have 3 tables

word(id, value);
word_categories(id, name);
word_category_word(word_category_id, word_id);

My relationships are MANY-TO-MANY.

My models are (typical code not included):

Word.php

    ...
    public function categories() : BelongsToMany
    {
        return $this->belongsToMany(WordCategory::class);
    }
    ...

WordCategory.php

    ...
    public function categories() : BelongsToMany
    {
        return $this->belongsToMany(Word::class);
    }
    ...

I also have 2 categories ( id: 1, id:2 ) and I want create words related to specific category, but my pivot table always empty and each word category has all words.

api.php

    ...
    Route::apiResource('wordCategories', WordCategoryController::class);
    Route::apiResource('wordCategories.words', WordController::class);
    ...

WordCategoryController.php

    ...
    public function store(StoreWordCategoryRequest $request)
    {
        return new WordCategoryResource(WordCategory::create($request->all()));
    }
    ...

WordController.php

    ...
    public function store(StoreWordRequest $request)
    {
        return new WordResource(Word::create($request->all()));
    }
    ...

I use this url:

POST:
api/v1/wordCategories/1/words/
body:
 {
   "value": "test"
 } 

I expect that after call api/v1/wordCategories/1/words/ will create word only for provided (1) word category. What should I do to get logic which I want?

CodePudding user response:

You've named your relation function wrong if you are following laravel convention.
try this :
Word.php :

public function word_categories() : 
    {
        return $this->belongsToMany(WordCategory::class);
    }

WordCategory.php

public function words() : 
    {
        return $this->belongsToMany(Word::class);
    }

and in your WordController:

    ...
    public function store(Request $request,$id)
    {
        $data = $request->all();
        $word_category = WordCategory::find($id);
        $word = new Word;
        $word->value = $data['value'];
        $word_category->words()->attach(word);
    }
    ...

This will add the word that you passed it's value to the category (value in request body) that you passed the id (1) in the api.

  • Related