davidvera
2 years ago

CRUD with a form generated dynamically ...

Posted 2 years ago by davidvera

I created a form which allows to publish several langs. After defining the langs, I want user to create a default category and save it ...

For this i create a view :

{!! Form::open( array('route' => 'setup.categoryCreate','method' => 'POST') ) !!}
<fieldset>
    <legend>Category</legend>

        @foreach($langs as $lang)

        <div class="form-group m-form__group">
            {{ Form::label( 'Category name in  ' . $lang->langname_en) }}
            {{ Form::text('catname_lang_' . $lang->id, 'Category name in ' . $lang->langname_en, [ 'class' => 'form-control m-input' ]) }}
        </div>
        <div class="form-group m-form__group">
            {{ Form::label( 'short name ' . $lang->langname_en ) }}
            {{ Form::text('catshortname_lang_' . $lang->id, 'Category short name in ' . $lang->langname_en, [ 'class' => 'form-control m-input' ]) }}
        </div>
    @endforeach
</fieldset>

As a result :

{ 
    "_token":"8N1dRDWTZz98hjE4a0dk86tvMJEexMoIAR0SViSO",
    "catname_lang_1":"Technologies de l'Information et de la Communication",
    "catshortname_lang_1":"TIC",
    "catname_lang_2":"Information & Communication Technology",
    "catshortname_lang_2":"ICT"
    ...
}

In my controller i Create an entry :

Category::create(array(
    'admin_id' => Auth::guard('admin')->user()->id,
    'created_at' => Carbon::now(),
    'updated_at' => Carbon::now(),
));

I have 2 tables :

categories
     id
     admin_id
     created_at
     updated_at
     deleted_at

langs
     id
     langname_fr
     langname
     ....

And a pivot table with contents :

 category_lang
     lang_id
     category_id
     catname
     catshortname
     ....

I should create 2 entries in the pivot table : "lang_id, category_id, catname_lang_1, catshortname_lang_1" And "lang_id, category_id, catname_lang_2, catshortname_lang_2" are 2 entries in different langs for the same category...

We can get lang_id here : catshortname_lang_2

My problem is to insert datas in different entries...

Usually in simple crud in the store method i write :

public function store (Request $request) {
    request()->validate([
        'catname' => 'required',
        'catshortname' => 'required',
    ]);
    Category::create($request->all());
    return redirect()->route(categories.index)->with('success', 'OK!!');
}

When i create a new category, i have several fields that are matching to specific table field ... how do i manage to create entries in pivot table ?

Thanks !

Please sign in or create an account to participate in this conversation.