D
D
devAston2019-09-11 13:11:40
Laravel
devAston, 2019-09-11 13:11:40

Laravel-admin doesn't render in belongsToMany form, what are the options?

There is a Promo model:

protected $table = 'promo';
// ...
public function locations()
{
    return $this->belongsToMany(Cities::class, 'cities_promo');
}

Controller code in laravel-admin
protected function form()
{
    $location = Cities::pluck('name', 'id');

    $form = new Form(new Promo);

    $form->text('title', __('Наименование'));
    $form->textarea('desc', __('Описание'));
    $form->multipleSelect('locations')->options($location);

    return $form;
}

The bottom line is that it does not display the values ​​that were previously selected and saved.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devAston, 2019-09-11
@devAston

An intermediate solution was to use an attribute.
It is necessary that the format for multipleSelect (and others) be in the array format [1,2,3 ... ,7].
During normal communication,

array of the form
{
['id' => 1,
'name' => 'Moscow',
...
],
['id' => 2,
'name' => 'Ekb',
...
],
}

Therefore, for formalization, I used a third-party attribute " Cities " to the " Promo " model.
End code
...
    //Add extra attribute
    //These attributes will be written to the database, if you do not want this, then do not advertise!
    //protected $attributes = ['cities'];

    //Make it available in the json response
    protected $appends = ['cities'];
    public function getCitiesAttribute()
    {
        return $this->locations->pluck('id');
    }

    public function setCitiesAttribute($value)
    {
        $this->locations()->sync($value);
    }

If there are other suggestions, I'm ready to listen.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question