D
D
Dmitry Averin2017-11-28 11:01:09
ORM
Dmitry Averin, 2017-11-28 11:01:09

Should the controller code be simplified to keep dynamic form models?

Hello, friends!
Please advise whether it is necessary to simplify (refactor) the controller code to save models of the "Product Card" dynamic form? The fields of the main model (typical product properties) are static, the fields of product images of the auxiliary model are dynamic.
I am especially interested in whether it is possible (and necessary!) not to wait for the main model to be saved in the database and to bind dynamic fields to the main One To Many "on the fly"? Now I'm waiting for the id of the main model - how to do this?

Click me -> ProductController.php
public function store(Request $request)
    {

        // Сохраняем поле "Название продукта" основной модели и получаем id записи
        $product_title = (['product_title' => $request->product_title]);     
        $product_title = Product::create($product_title);   
        
        //Транспонируем массив и сохраняем динамические поля "Изображений"
        //Cвязь основной и дочерней модели One To Мany
        //https://laravel-news.ru/blog/tutorials/cleaning-up-form-input-with-transpose

        $requestData = collect($request->only('photo_filenames', 'photo_titles', 'photo_descs'));

        $photos = $requestData->transpose()->map(function ($photoData) {
        return new Photo([
            'photo_filename'    => $photoData[0], 
            'photo_title'       => $photoData[1],           
            'photo_desc'        => $photoData[2],
         ]);       
        });

        Product::find($product_title->id)->photos()->saveMany($photos);

        return back();        

    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
JhaoDa, 2017-11-28
@JhaoDa

Need. Just do not refactor, but start by learning Laravel (and PSR-2/12 is a must).

I am especially interested in whether it is possible (and necessary!) not to wait for the main model to be saved in the database and to bind dynamic fields to the main One To Many "on the fly"? Now I'm waiting for the id of the main model - how to do this?
You can, uuid will help.

R
Roman Sokharev, 2017-11-28
@greabock

My eyes... Man, you should really tighten up the base in puff. Chet is absolutely bad for you. Some kind of indistinct juggling with unnecessary variables.

public function store(Request $request)
{
    Product::create($request->only('product_title'))->photos()->saveMany(array_map(function($photo_filename,  $photo_title, $photo_desc){
        return new Photo(compact('photo_filename', 'photo_title', 'photo_desc'));
    },  ...$request->only('photo_filenames', 'photo_titles', 'photo_descs')));
    
    return back();
}

M
markinigor, 2017-11-28
@markinigor

Another option is to immediately create a product blank and pass it in the create method

public function create(Product $product)
    {
        if (! $product->exists) {
            $product = $this->createAndReturnSkeletonProduct(); //создаешь в методе заготовку, с нужными тебе полями
            return redirect()->route('products.create', $product);
        }
        
        return view('products.create', compact('product')]); 
    }

// И пару роутов ведущих в один метод контроллера:
    Route::get('products/create', '[email protected]')->name('products.create.start');
    Route::get('products/{product}/create', '[email protected]')->name('products.create');

And you will always have a product created earlier before its links.
Clean up blanks periodically.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question