question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Field select2_multiple problems when using Laravel 5.2 Model with custom Join/Pivot Table

See original GitHub issue

Hey, I might be using this wrong… but I didn’t see in documentation where to get this to work. Documentation: https://laravel-backpack.readme.io/docs/crud-fields#select2_multiple-n-n-relationship I’m using a custom Pivot Table for many-to-many relationship (https://laravel.com/docs/5.2/eloquent-relationships#many-to-many).

Challenge.php model:

...
    public function teams()
    {
        return $this->belongsToMany('App\Team', 'challenge_team', 'challenge_id', 'team_id')->withTimestamps();
    }
...

_ChallengeCrudController.php :_

...
        $this->crud->addField(
            [       // Select2Multiple = n-n relationship (with pivot table)
                'label' => "Teams Involved",
                'type' => 'select2_multiple',
                'name' => 'teams', // the method that defines the relationship in your Model
                'entity' => 'teams', // the method that defines the relationship in your Model
                'attribute' => 'team_name', // foreign key attribute that is shown to user
                'model' => "App\Team", // foreign key model
                'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
            ]
        );
...

Doing this… I was able to select and SAVE NEW Challenges with multiple Teams, but I was unable to EDIT and see the previously selected Teams. It did persist to database… but didn’t render them in view properly.

I did the following to make it work: _ChallengeCrudController.php :_

...
        $this->crud->addField(
            [       // Select2Multiple = n-n relationship (with pivot table)
                'label' => "Teams Involved",
                'type' => 'select2_multiple',
                'name' => 'teams', // the method that defines the relationship in your Model
                'entity' => 'teams', // the method that defines the relationship in your Model
                'attribute' => 'team_name', // foreign key attribute that is shown to user
                'model' => "App\Team", // foreign key model
                'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
                'foreign_pivot_key' => 'team_id'
            ]
        );
...

Then added the foreign_pivot_key to select2_multiple.blade.php file:

...
<!-- select2 multiple -->
<div class="form-group">
    <label>{{ $field['label'] }}</label>
    <?php
    $field['foreign_pivot_key'] = !empty($field['foreign_pivot_key']) ? $field['foreign_pivot_key'] : 'id';
    ?>
    <select
        class="form-control select2"

    @foreach ($field as $attribute => $value)
        @if (is_string($attribute))
            @if ($attribute=='name')
                {{ $attribute }}="{{ $value }}[]"
            @else
                {{ $attribute }}="{{ $value }}"
            @endif
        @endif
    @endforeach
    multiple>
    <option value="">-</option>

    @if (isset($field['model']))
        @foreach ($field['model']::all() as $connected_entity_entry)
            <option value="{{ $connected_entity_entry->getKey() }}"
                    @if ( (isset($field['value']) && in_array($connected_entity_entry->getKey(), $field['value']->lists($field['foreign_pivot_key'])->toArray())) || ( old( $field["name"] ) && in_array($connected_entity_entry->getKey(), old( $field["name"])) ) )
                    selected
                @endif
            >{{ $connected_entity_entry->{$field['attribute']} }}</option>
            @endforeach
            @endif
            </select>
</div>
...

Let me know if that’s a good work-around.

LOVE THE BACKPACK packages!!!

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:11 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
pxpmcommented, Feb 19, 2019

@LinLin520 shouldn’t you alse set pivot => true in field definition ?

1reaction
BinaryBlockcommented, Aug 15, 2016

Could you please try it when you have the time and tell me if it works for you too? If so, I’ll push the update immediately.

Ahhh… you rock! Yes, it worked great. Smart idea about grabbing pivot info from object. Push away. image

Read more comments on GitHub >

github_iconTop Results From Across the Web

Laravel 5.2 three-way pivot with custom pivot model
So for example if i want to print all the contacts and their contact_types for a department then i can do something like...
Read more >
Eloquent: Relationships - The PHP Framework For Web Artisans
If you would like to define a custom model to represent the intermediate table of your many-to-many relationship, you may call the using...
Read more >
Eloquent: Getting Started - Laravel - The PHP Framework For ...
When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving ...
Read more >
Eloquent: Relationships - The PHP Framework For Web Artisans
Eloquent makes managing and working with these relationships easy, ... a third argument to the belongsTo method specifying your parent table's custom key:....
Read more >
Database Testing - The PHP Framework For Web Artisans
In addition, Laravel model factories and seeders make it painless to create ... the value of each column when you create this test...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found