在 laravel 中动态无限制地添加字段

Posted

技术标签:

【中文标题】在 laravel 中动态无限制地添加字段【英文标题】:Add fields in laravel dynamically and unlimited 【发布时间】:2018-02-16 19:56:35 【问题描述】:

我的网站有一部分用户或管理员可以在其中添加餐厅列表(真的很像帖子,只是命名不同)

有一些固定输入,例如(标题、描述和地图) .

所以我需要的是 + 按钮,人们可以在其中添加字段并用另一个字段命名菜单项,以显示每个项目的价格。

所以我的问题是如何实现这个选项?

我现在有什么?

餐厅迁移:

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

【问题讨论】:

您可以将菜单作为 json 格式存储在数据库中,这样每个餐厅都可以拥有自己的 json 对象和不同的食物选项,即使您可以在其中存储 html 属性 @AnarBayramov 我不知道该怎么做!你能帮我给我一个样品吗? w3schools.com/js/js_json_php.asp 您好,这是您想要实现的目标吗?如果没有,请更准确地告诉我细节.. embed.plnkr.co/HQOuNvDfDwkR2uLD632u @demonyowh 嗨,兄弟,这正是我的表单所需要的 + 现在我正在使用 sreejith bs 代码来存储有效的数据,但也可以保存额外的空输入。所以现在我需要这些:停止额外的空输入以保存并在我的表单中使用您的方法。请在 sreejith 上查看我的 cmets 答案,了解我对额外空输入的含义。 【参考方案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

希望它有意义。

【讨论】:

这部分// Save in DB 我假设我必须用menuprice 的行创建新表对吗? 不需要。只需将该 json 保存在一个表格列中,例如 custom_menu_price 这样您以后可以轻松地从 DB 中检索为 KEY PAIR 值。 我做了所有这些,我在存储方法上没有错误,现在请告诉我如何查看该 json 文件保存的位置,以及如何在前端显示它?我总共是 0 :) 您是否在迁移中添加了额外的行?

以上是关于在 laravel 中动态无限制地添加字段的主要内容,如果未能解决你的问题,请参考以下文章

在动态创建的输入上使用laravels {{old}}

Laravel 表单请求动态字段在重定向时消失

laravel 中动态输入字段的验证

动态添加字段到 laravel 表单

laravel 5.3 - 在刀片模板中显示来自 mysql 文本字段的 json 数据

如何使laravel中的动态表单字段可填写