Добавляйте поля в laravel динамически и без ограничений

У меня есть часть моего веб-сайта, где пользователи или администраторы могут добавлять список ресторанов (это действительно похоже на сообщения, просто другое название)

Есть некоторые фиксированные входные данные, такие как (название, описание и карта). Мне также нужна часть, где пользователи/администраторы могут добавлять меню ресторанов. Эти параметры, очевидно, могут быть разными для каждого ресторана, поскольку их меню представляет собой короткий список или длинный список.

Итак, мне нужна кнопка +, где люди могут добавлять поля и называть свои пункты меню другим полем для цены каждого элемента.

Итак, мой вопрос: как добиться этого варианта?

Что я имею на данный момент?

Миграция ресторана:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRestaurantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('restaurants', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->string('slug')->unique();
            $table->string('description')->nullable();
            $table->string('image')->nullable();
            $table->string('menu')->nullable();
            $table->string('address')->nullable();
            $table->integer('worktimes_id')->unsigned();
            $table->integer('workday_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->string('verified')->default(0);
            $table->string('status')->default(0);
            $table->timestamps();
        });

        Schema::table('restaurants', function($table) {
            $table->foreign('worktimes_id')->references('id')->on('worktimes');
            $table->foreign('workday_id')->references('id')->on('workdays');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('restaurants');
    }
}

На этом все, я так и не стал создавать CRUD контроллер для ресторана, так как держусь за этот вариант и ваши мнения.

Спасибо.

ОБНОВЛЕНИЕ

СПОСОБ ХРАНЕНИЯ:

public function store(Request $request)
    {
      //Validating title and body field
      $this->validate($request, array(
          'title'=>'required|max:225',
          'slug' =>'required|max:255',
          'image' =>'sometimes|image',
          'description' => 'required|max:100000',
          'address' => 'sometimes|max:500',
          'user_id' => 'required|numeric',
          'verified' => 'sometimes',
          'status' => 'required|numeric',
        ));

      $restaurant = new Restaurant;

      $restaurant->title = $request->input('title');
      $restaurant->slug = $request->input('slug');
      $restaurant->description = $request->input('description');
      $restaurant->address = $request->input('address');
      $restaurant->user_id = $request->input('user_id');
      $restaurant->verified = $request->input('verified');
      $restaurant->status = $request->input('status');



      if ($request->hasFile('image')) {
        $image = $request->file('image');
        $filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/');
        $request->file('image')->move($location, $filename);


        $restaurant->image = $filename;
      }


      // menu
      $newArray = array();
      $menuArray = $request->custom_menu; //Contains an array of Menu Values
      $priceArray = $request->custom_price;   //Contains an array of Price Values

      //Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
      foreach ($menuArray as $key => $singleMenu) {
          $newArray[$singleMenu] = $priceArray[$key];
      }
      //Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")

      //Converting array to json format to store in your table row 'custom_menu_price'
      $jsonFormatData = json_encode($newArray);
      //Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}

      // Save in DB
      //
      //
      //

      // To retrieve back from DB to MENU and PRICE values as ARRAY
      $CustomArray = json_decode($jsonFormatData, TRUE);
      foreach ($CustomArray as $menu => $price) {
          echo "Menu:".$menu."<br>";
          echo "Price:".$price."<br>";
      }
      // menu


      $restaurant->save();

      $restaurant->workdays()->sync($request->workdays, false);
      $restaurant->worktimes()->sync($request->worktimes, false);

      //Display a successful message upon save
      Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
      return redirect()->route('restaurants.index');

person mafortis    schedule 08.09.2017    source источник
comment
вы можете хранить меню как json в базе данных, чтобы каждый ресторан мог иметь свой собственный объект json с различными вариантами еды, даже если вы можете хранить там свойства html   -  person Anar Bayramov    schedule 08.09.2017
comment
@AnarBayramov Я понятия не имею, как это сделать! не могли бы вы помочь мне с предоставлением мне образца?   -  person mafortis    schedule 08.09.2017
comment
w3schools.com/js/js_json_php.asp   -  person Anar Bayramov    schedule 08.09.2017
comment
привет, это то, чего вы хотите достичь? если нет, сообщите мне подробности поточнее.   -  person Demonyowh    schedule 11.09.2017
comment
@demonyowh привет, братан, это именно то, что мне нужно для моей формы + теперь я использую коды sreejith bs для хранения данных, которые работают, но также сохраняют дополнительный пустой ввод. Итак, теперь мне нужно это: остановить этот дополнительный пустой ввод для сохранения и использовать ваш метод в моей форме. Пожалуйста, посмотрите мои комментарии к ответу sreejith, чтобы понять, что я имею в виду под дополнительным пустым вводом.   -  person mafortis    schedule 11.09.2017


Ответы (1)


Что вы можете сделать, это

1) добавьте еще одну строку таблицы для custom_menu_price в файл миграции

$table->string('custom_menu_price')->nullable();

2) Измените свой form

<form method="POST" action="{{ ...... }}">
    {{ csrf_field() }}

    //I'm Looping the input fields 5 times here
    @for($i=0; $i<5; $i++)
        Enter Menu {{ $i }} : <input type="text" name="custom_menu[]">  //**Assign name as ARRAY
        Enter Price {{ $i }} : <input type="text" name="custom_price[]">  //**Assign name as ARRAY
        <br><br>
    @endfor

    <input type="submit" name="submit">
</form>

3) В вашем controller

public function store(Request $request) {

    //Validating title and body field
    $this->validate($request, array(
      'title'=>'required|max:225',
      'slug' =>'required|max:255',
      'image' =>'sometimes|image',
      'description' => 'required|max:100000',
      'address' => 'sometimes|max:500',
      'user_id' => 'required|numeric',
      'verified' => 'sometimes',
      'status' => 'required|numeric',
    ));

    $restaurant = new Restaurant;

    $restaurant->title = $request->input('title');
    $restaurant->slug = $request->input('slug');
    $restaurant->description = $request->input('description');
    $restaurant->address = $request->input('address');
    $restaurant->user_id = $request->input('user_id');
    $restaurant->verified = $request->input('verified');
    $restaurant->status = $request->input('status');

    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/');
        $request->file('image')->move($location, $filename);
        $restaurant->image = $filename;
    }

    // menu
    $newArray = array();
    $menuArray = $request->custom_menu; //Contains an array of Menu Values
    $priceArray = $request->custom_price;   //Contains an array of Price Values

    //Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
    foreach ($menuArray as $key => $singleMenu) {
      $newArray[$singleMenu] = $priceArray[$key];
    }
    //Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")

    //Converting array to json format to store in your table row 'custom_menu_price'
    $jsonFormatData = json_encode($newArray);
    //Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}

    // Save in DB
    $restaurant->custom_menu_price = $jsonFormatData;
    // menu

    $restaurant->save();

    $restaurant->workdays()->sync($request->workdays, false);
    $restaurant->worktimes()->sync($request->worktimes, false);

    //Display a successful message upon save
    Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
    return redirect()->route('restaurants.index');
}

внутри вашего представления front.restaurantshow:

@php
    // To retrieve back from DB to MENU and PRICE values as ARRAY
    $CustomArray = json_decode($restaurant->custom_menu_price, TRUE);
@endphp

@foreach ($CustomArray as $menu => $price)
    Menu Name: {{ $menu }} <br>
    Menu Price: {{ $price }} <br><br>
@endforeach

Надеюсь, это имеет смысл.

person Sreejith BS    schedule 08.09.2017
comment
в этой части // Save in DB я предполагаю, что должен создать новую таблицу со строками menu и price, верно? - person mafortis; 09.09.2017
comment
Не нужно. Просто сохраните этот json в одном столбце таблицы, скажем, custom_menu_price - person Sreejith BS; 09.09.2017
comment
Таким образом, вы можете легко получить из БД значения KEY PAIR позже. - person Sreejith BS; 09.09.2017
comment
я сделал все это, у меня нет ошибки в методе хранения, теперь, пожалуйста, скажите мне, как увидеть, где сохранен этот файл json, и как показать его во внешнем интерфейсе? я вообще 0 в этом :) - person mafortis; 09.09.2017
comment
Вы добавили дополнительную строку в миграцию? - person Sreejith BS; 09.09.2017
comment
Я изменил свой столбец menu на custom_menu_price - person mafortis; 09.09.2017
comment
Изменил мой ответ. - person Sreejith BS; 09.09.2017
comment
теперь работает, но мой вывод такой {"ARGQEH":"324235235","SAFGARG":"324325","":null} - person mafortis; 09.09.2017
comment
Да. его формат json. Используйте json_decode, чтобы вернуться как МЕНЮ и Цена отдельно. Обновил код. - person Sreejith BS; 09.09.2017
comment
так как исправить? - person mafortis; 09.09.2017
comment
Какую ошибку исправить? Узнайте больше о кодировании и декодировании json. stackoverflow.com/questions/30073065/ - person Sreejith BS; 09.09.2017
comment
нет ошибки, я просто хочу показать товары в виде списка, а не как {"ARGQEH":"324235235","SAFGARG":"324325","":null}, я хочу показать их в виде таблицы с их ценой. - person mafortis; 09.09.2017
comment
ты поверишь, если я скажу, что у меня настоящая головная боль? куда я должен добавить это json_decode(), которое вы добавили? - person mafortis; 09.09.2017
comment
Внутренние методы для перечисления ресторанов, вам нужно отдельно меню и цену. Вот где вы должны сделать json_decode, чтобы вернуть фактические данные. - person Sreejith BS; 09.09.2017
comment
если я добавлю его в свой метод show, я получу ошибку Undefined variable: jsonFormatData - person mafortis; 09.09.2017
comment
это мой метод show -> public function restaurantshow($slug) { $restaurant = Restaurant::where('slug', $slug)->firstOrFail(); return view('front.restaurantshow', compact('ресторан')); } - person mafortis; 09.09.2017
comment
Потому что, когда вы сохранили их как json в БД, может быть нуль. Возможно, вы не указали МЕНЮ или ЦЕНУ при отправке формы. - person Sreejith BS; 09.09.2017
comment
я только что выполнил 3 строки, а остальные 2 я не сделал. - person mafortis; 09.09.2017
comment
Дайте какое-нибудь условие, чтобы проверить, является ли оно нулевым, прежде чем сохранять в БД как json. - person Sreejith BS; 09.09.2017
comment
хмммм :-D если бы я знал, как работать с этим json, зачем бы я спрашивал здесь :-p - person mafortis; 09.09.2017