Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add fields in laravel dynamically and unlimited

Tags:

I have part of my website where users or admins can add restaurant list (is really like posts, just different naming)

There is some fixed inputs such as (title, description and map) I also need a part where users/admins can add restaurants menu this options is obviously can be different for each restaurant as their menu is a short list or long list.

So what I need is like + button where people can add fields and named their menu items with another field for the price of each item.

So my question is how to achieve this option?

What do I have at the moment?

Restaurant migrate:

<?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');
    }
}

That's all, I still didn't create CRUD controller for restaurant because I'm holding for this option and your opinions.

Thanks.

UPDATE

STORE METHOD:

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');
like image 713
mafortis Avatar asked Sep 08 '17 01:09

mafortis


1 Answers

What you can do is

1) add another one table row for custom_menu_price in your migration file

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

2) Modify your 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) In your 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');
}

inside your front.restaurantshow view:

@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

Hope it makes sense.

like image 183
Sreejith BS Avatar answered Oct 12 '22 14:10

Sreejith BS