A
A
Al Sm2018-03-07 14:45:11
Laravel
Al Sm, 2018-03-07 14:45:11

How to organize saving values ​​(morphedByMany)?

Hello, I need help, I'm confused!
The idea is this: to have a table with additional fields to the form (which can then be added to different forms of models: News, Blog ...) The
question is how to display these fields correctly and save the values?
In the form, we can send and display all the fields with a foreword 'fields' => Field::all(), but how to fill them with values ​​related to a specific Blog entry?
How to save the values ​​correctly?
Some code:
Blog.php

class Blog extends Model
{
...
    public function fields()
    {
        return $this->morphToMany(Field::class, 'fieldable');
    }
}

field.php
class Field extends Model
{
...
    public function blogs()
    {
        return $this->morphedByMany(Blog::class, 'fieldable');
    }
}

BlogController.php
class BlogController extends Controller
{
...
    public function edit(Blog $blog)
    {
        $blog= Blog ::find($id);
        return view('blog::blog.form', [
            'blog' => $blog,
            'fields' => Field::all()
        ]);
    }
...
}

form.blade.php
@if($fields->count())
    @foreach ($fields as $field)
        //выводим все доп. поля (type="text") c name="$field->slug"
        <div class="form-group">
            {{ Form::Text($field->slug) }}
        </div>

    @endforeach
@endif

The only thing that comes to mind so far is to send all additional fields and all related fields with values ​​to the form, then compare and fill in. But there must be a better way!? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Nagorny, 2018-03-07
@radio_mus

In laravel's
dock The output is simpleforeach $blog->fields as item

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question