0

I currently have a users table and a books table, with a pivot table user_book which has user_id, book_id as well as book_tag (this can be 'H' for happy, 'S' for sad or 'A' for angry)

Against the advice of the backpack team, we are looking to have three multiselect options, which will popoulate with the 3 different types of book tags, i.e. Happy books, Sad books, and Angry books.

I currently have the following definition inside the initFields function:

<?php 
namespace App\Http\Controllers\Admin;

class UserCrudController extends UserCrudController
{
    // ....

    protected function initFields()
    {
        // crud fields here
        $this->crud->addField([
            'label' => "Happy books",
            'type' => 'select2_multiple',
            'name' => 'books_h',
            'entity' => 'books',
            'model' => "App\Models\Book",
            'pivot' => true,
        ]);
    }
}

This however, does not seem to save. Any assistance is greatly appreciated

cross19xx
  • 3,170
  • 1
  • 25
  • 40
  • Check this one, seems to have a similar problem as you https://stackoverflow.com/questions/56495180/backpack-laravel-manage-extra-columns-in-pivot-table-in-a-many-to-many-relations – Kevin Aug 02 '22 at 14:54
  • @workservice, it appears they're using a custom select... Also, I have to mention I just started backpack – cross19xx Aug 02 '22 at 15:00

1 Answers1

0

you need to make sure the the relation books_h is defined correctly in your entity as belongsToMany relationship based on laravel docs https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

like so

public function books_h(): 
 \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Book::class, 'user_book', 'user_id', 'book_id', 'id', 'id')->withPivot('book_tag');
    }

then you need to overwrite both create and update methods to update the request for these fields to transfer it to look like so

[
    1 => ['book_tag' => 'H'],
    2 => ['book_tag' => 'H'],
]

before calling $response = $this->traitUpdate(); refer to this link for more info https://backpackforlaravel.com/docs/5.x/crud-operation-update#override-the-update-method

but I would recommend to use the correct way backpack team mentions https://backpackforlaravel.com/docs/5.x/crud-fields#save-additional-data-to-pivot-table even if you want to have it as 3 separate fields you can define the subfields as hidden with the value you want