Adding fields to laravel dynamically and unlimitedly

I have a part of my site where users or administrators can add a list of restaurants (in fact, it looks like messages, just different names)

There are some fixed inputs, such as (name, description and map). I also need a part in which users / admins can add restaurant menus. These parameters, obviously, can be different for each restaurant, since their menu is a short list or a long list.

So, I need a + button, where people can add fields and call their menu items a different field for the price of each item.

So my question is how to achieve this option?

What do I have at the moment?

Restaurant Migration:

<?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- , .

.

UPDATE

:

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');
+4
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

, .

+2

Source: https://habr.com/ru/post/1685270/


All Articles