-1

My system creates a food dish and saves it in the database, what I want is that to that dish I just created add one or several ingredients selected through a checkbox of a list already made dynamic. this would see the view

as you can see I selected the pizza as a previously created dish. now I only need to add the ingredients with their respective amount.

say that if the user does not select the checkbox he will not add the ingredient.

plato migration

<?php

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

class CreatePlatosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('platos', function (Blueprint $table) {
            $table->increments('id');
            $table->char('nombre',50);
            $table->double('valor', 8, 2);
            $table->timestamps();
        });
    }

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

platoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Plato;
use App\Ingrediente;
use App\PlatoIngrediente;


class PlatoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    $platos = Plato::all();


    return view('platos/index', compact('platos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('platos/create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'nombre' => 'required|max:50',
            'valor' => 'required|max:50'
        ]);
        $plato = Plato::create($validatedData);

        return redirect('/platos')->with('success','El Plato se guardó correctamente en la base de datos');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $plato = Plato::findOrFail($id);

        return view('platos/edit', compact('plato'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'nombre' => 'required|max:50',
            'valor' => 'required|numeric'
        ]);
        Plato::whereId($id)->update($validatedData);

        return redirect('/platos')->with('success', 'El Plato se actualizó correctamente en la base de datos');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $plato = Plato::findOrFail($id);
        $plato->delete();

        return redirect('/platos')->with('success', 'El Palto se eliminó correctamente en la base de datos');
    }
}

platoIngrediente migration

<?php

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

class CreatePlatosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('platos', function (Blueprint $table) {
            $table->increments('id');
            $table->char('nombre',50);
            $table->double('valor', 8, 2);
            $table->timestamps();
        });
    }

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

platoIngrediente controller

<?php

namespace App\Http\Controllers;

use App\PlatoIngrediente;
use App\Plato;
use App\Ingrediente;
use Illuminate\Http\Request;

class PlatoIngredienteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $platos = Plato::all();
    return view('platoingrediente/index', compact('platos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $platos = Plato::all();
        $ingredientes = Ingrediente::all();
        return view('platoingrediente/create', compact('platos','ingredientes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $validatedData = $request->validate([
          'nombre' => 'required|max:50',
          'valor' => 'required|max:50',
      ]);




        $validatedData2 = $request->validate([
          'id_plato' => 'required|max:50',
          'id_ingrediente' => 'required|max:50',
          'cantidad' => 'required|max:50'
        ]);

        $plato = Plato::create($validatedData);
      $ingrediente = Ingrediente::Create($validateData2);

      return redirect('/platos')->with('success','El Plato se guardó correctamente en la base de datos');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

and the view platoingrediente/create

@extends('layouts.app')

@section('content')

<script>
          function showContent(el) {
          var element = el.parentNode.parentNode.nextElementSibling.querySelector('.dv');
          if (el.checked) {
            element.style.display='block';
          }
          else {
            element.style.display='none';
          }
          }
</script>


<div class="up sombra card">
  <div class="card-header">
    Creacion del plato
  </div>
  <div class="card-body">
    <div class="up">
  @if(session()->get('success'))
    <div class="alert alert-success">
      {{ session()->get('success') }}
    </div><br />
  @endif



  <dd>Primero selecciona un plato en el sistema: </dd>
  <select name="" class="form-control">
  <option selected>[ SELECCIONA UN PLATO ]</option>
   @foreach( $platos as $plato )
  <option value="{{ $plato->id }}">{{ $plato->nombre }}</option>
 @endforeach
</select>


    <div class="text-center up">
      <label class="name">  Agregar Ingredientes a el plato </label>
  </div>

<table class="table table-striped">
  <thead>
    <tr>
      <td>ID</td>
      <td>Nombre del Ingrediente</td>
      <td>Proveedor</td>
      <td>Agregar</td>
      <td>Cantidad</td>
    </tr>
  </thead>
  <tbody>
      @foreach($ingredientes as $ingrediente)
      <tr>
          <td>{{$ingrediente->id}}</td>
          <td>{{$ingrediente->nombre}}</td>
          <td>{{$ingrediente->proveedor}}</td>
          <td>

              <label>
            <input type="checkbox" name="check" id="check" value="" onchange="javascript:showContent(this)" />
          </label>

          </td>
          <td>
            <div class="form-group row">
             <div class="col-sm-4">
               <div class="dv" style="display:none;">
            <input class="dvs" type="number" />
            </div>
          </div>
          </div>
          </td>
      </tr>
      @endforeach
  </tbody>
</table>


</div>


</div>
</div>
@endsection

if you need more info like the models, please comment, if you need more explanation also comment!

Myers
  • 148
  • 8
  • 1
    I dont quite understand what is your question? https://stackoverflow.com/questions/1809494/post-unchecked-html-checkboxes – Jraaaa May 21 '19 at 07:20
  • @Jraaaa I need to add the ingredients to the dishes by means of foreign keys, and then call the dishes and show a view with all their ingredients. – Myers May 21 '19 at 07:27

1 Answers1

0

Create a many to many relationship between a dishes (Plato) and ingredients (Ingrediente) (many dishes can have many ingredients).

The following assumes you have a model for both Ingrediente and Plato

create a pivot table:

public function up()
    {
        Schema::create('plato_ingrediente', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('plato_id')->unsigned();
            $table->integer('ingrediente_id')->unsigned();
        });
    }

Add relationships to the models:

Plato Model:

public function ingredientes()
{
    return $this->belongsToMany('App\Plato');
}

Ingrediente Model

public function platos()
    {
        return $this->belongsToMany('App\Ingrediente');
    }

Using input from a checkbox with the ingrediente id as it's value add the ingrediente to the plato:

$plato = Plato::find($id);
$plato->ingredientes()->attach($ingrediente_id);

Retrieve the ingredientes from a plato:

$plato = Plato::find($id);
$ingredientes = $plato->ingredientes //returns a collection of ingredientes
$foreach($ingredientes as $ingrediente)
{
    //do something e.g.
    echo $ingrediente->id;
}
Ryan J Field
  • 189
  • 7