Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Model and many-to-many relations in select field #24

Open
henninghorn opened this issue Jul 10, 2018 · 0 comments
Open

Model and many-to-many relations in select field #24

henninghorn opened this issue Jul 10, 2018 · 0 comments

Comments

@henninghorn
Copy link

henninghorn commented Jul 10, 2018

Hi @netojose

I'm building a form for a model (Venue), which can have multiple tags (many-to-many relationship)
When I'm editing a form, I would like to see which tags that are already added to the venue model.

To do so, it seems like you need to have a very specific data structure:

{!! Form::select('tags', 'Select tags', [1 => 'Some tag', 2 => 'Another tag'])->multiple() !!}

This means, that you cannot do something like this:

// Controller
$tags = Tag::all();
return view('venue.edit', ['tags' => $tags]);

// Blade
{!! Form::select('tags', 'Select tags', $tags)->multiple() !!}

Instead you need to do this to accomplish the correct data structure and have existing relationships selected:

// edit method in controller
$model = $venue->toArray();
$model['tags'] = $venue->tags->pluck('name', 'id')->all();

$data = [
    'model' => $model,
    'tags' => Tag::all()->pluck('name', 'id')->all()
];

return view('venue.edit', $data);

Is this by design how you should handle such forms? E.g. forms which has relationships with other models? Like a blog post with tags?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant