Home > Software design >  Show an attribute from another table in a form instead the Foreign Key LARAVEL
Show an attribute from another table in a form instead the Foreign Key LARAVEL

Time:09-01

Hi im new in Laravel and im trying to create a CRUD with some relationships between tables, I want to make a form to create/edit and show an attribute from another table in the database, instead of the Foreign Key something like this:

https://i.stack.imgur.com/vsw1K.png

And not like this:

https://i.stack.imgur.com/xfLaz.png

This is my code:

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Tabla extends Model
{
    use HasFactory;

    public function clientes()
    {
        return $this->hasMany(Tabla::class, 'Tabla_id', 'id');
    }

}

Controller:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreReparacionRequest;
use App\Http\Requests\UpdateReparacionRequest;
use App\Models\Reparacion;
use App\Models\Cliente;
use App\Models\Tabla;

class ReparacionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()

    {
        $reparaciones = Reparacion::orderBy('id', 'desc')->get();



        return view('reparacion.index', compact('reparaciones'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $tablas = Tabla::all();
        $clientes = Cliente::all();


        //$tablas=Tabla::pluck('Modelo,','id');
        return view('reparacion.create' , compact('tablas','clientes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreReparacionRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreReparacionRequest $request)
    {
        $datos_reparacion = $request->except('_token');
        Reparacion::insert($datos_reparacion);
        return response()->json($datos_reparacion);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Reparacion  $reparacion
     * @return \Illuminate\Http\Response
     */
    public function show(Reparacion $reparacion)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Reparacion  $reparacion
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $reparacion=Reparacion::findOrFail($id);
        $tablas = Tabla::all();
        


        return view('reparacion.edit', compact('reparacion','tablas'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateReparacionRequest  $request
     * @param  \App\Models\Reparacion  $reparacion
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateReparacionRequest $request, $id)
    {
        $datos_reparacion = $request->except('_token','_method');
        Reparacion::where('id','=', $id)->update($datos_reparacion);
        $reparacion=Reparacion::findOrFail($id);
        return view('reparacion.edit', compact('reparacion'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Reparacion  $reparacion
     * @return \Illuminate\Http\Response
     */
    public function destroy( $id)
    {
        Reparacion::destroy($id);
        return redirect('reparaciones')->with('success', 'Reparación eliminada');
    }
}

View:

<label for="Tabla_id">
    Tabla</label>
<select name="Tabla_id" id="Tabla_id">
    @foreach ($tablas as $tabla)
        <option value="{{ isset($tabla->Modelo) ? $tabla->Modelo : '' }}">{{ $tabla->Modelo }}</option>
    @endforeach
</select><br>
<label for="Cliente_id">
    Cliente
</label>
<input type="text" name="Cliente_id" placeholder="Cliente"
    value="{{ isset($reparacion->Cliente_id) ? $reparacion->Cliente_id : '' }}
">
<br>
<label for="Reparacion">Reparacion</label>
<input type="text" name="Reparacion" id="Reparacion"
    value="{{ isset($reparacion->Reparacion) ? $reparacion->Reparacion : '' }}
"><br>
<label for="Fecha_llegada">Fecha de llegada</label>
<input type="date" name="Fecha_llegada" id="Fecha_llegada"
    value="{{ isset($reparacion->Fecha_llegada) ? $reparacion->Fecha_llegada : '' }}"><br>
<label for="Fecha_salida">Fecha de salida</label>
<input type="date" name="Fecha_salida" id="Fecha_salida"
    value="{{ isset($reparacion->Fecha_salida) ? $reparacion->Fecha_salida : '' }}"><br><br>
<label for="Estado">Estado</label>
<input type="text" name="Estado" id="Estado"
    value="{{ isset($reparacion->Estado) ? $reparacion->Estado : '' }}
"><br><br>
<label for="Precio">Precio</label>
<input type="text" name="Precio" id="Precio"
    value="{{ isset($reparacion->Precio) ? $reparacion->Precio : '' }}
"><br><br>
<label for="Observaciones">Observaciones</label>
<input type="text" name="Observaciones" id="Observaciones"
    value="{{ isset($reparacion->Observaciones) ? $reparacion->Observaciones : '' }}
"><br>
<input type="submit" value="Enviar">

Ive tried to add this code in the view:

<select name="Cliente_id" id="Cliente_id">
    @foreach ( $clientes as $cliente )
        <option value=""{{ isset($cliente->Nombre) ? $cliente->Nombre : '' }}"">{{$cliente->Nombre }}
        </option>
    @endforeach
</select>

and this on the controller:

  public function edit($id)
    {
        $reparacion=Reparacion::findOrFail($id);
        $tablas = Tabla::all();
        $clientes = Cliente::all();


        return view('reparacion.edit', compact('reparacion','tablas','clientes'));
    }

but it gave me an error;

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: reparacions.Cliente_id

CodePudding user response:

In your view:

<option value="{{ isset($tabla->Modelo) ? $tabla->Modelo : '' }}">{{ $tabla->Modelo }}</option>

And

<option value=""{{ isset($cliente->Nombre) ? $cliente->Nombre : '' }}"">{{$cliente->Nombre }}</option>

Focus on this part isset($tabla->Modelo) & isset($cliente->Nombre), you are passing string/empty value. While this data passes through controller to database, it will converted/denoted as null value. That's why you face this error:

In order to make work, you need to pass fully satisfied foreign id $tabla->id and $cliente->id to the value attribute in option tag.

<select name="Tabla_id" id="Tabla_id">
    @foreach ($tablas as $tabla)
        <option value="{{ $tabla->id }}">{{ $tabla->Modelo }}</option>
    @endforeach
</select> 

And

<select name="Cliente_id" id="Cliente_id">
    @foreach ( $clientes as $cliente )
        <option value="{{ $cliente->id }}">{{ $cliente->Nombre }}</option>
    @endforeach
</select>
  • Related