Laravel 5.6: show field of one table related to another by another field

0

I'm creating a small CRM application.

I get the following error when I try to show the client's name in the edit meeting view

  

Trying to get property of non-object (View:   /resources/views/employee/reunion/edit.blade.php)

 <option value="<?php echo e($reunion->cliente_id); ?>" selected hidden><?php echo e($reunion->cliente->nombre); ?></option>

I have the following models, drivers and views of Clients and Meetings:

Cliente.php

    <?php

namespace App;

use App\Filters\ClienteFilter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Cliente extends Model
{
    protected $fillable = ['nombre', 'email','direccion', 'telefono', 'nif', 'esEmpresa', 'comercial_id', 'riesgo', 'notas'];
    //Un cliente puede tener asociadads muchas reuniones
    public function reunion(){
        return $this->hasMany(Reunion::class);
    }  
    //Constructor de filtros para el usuario
    public function scopeFilter(Builder $builder, $request)
    {
        return (new ClienteFilter($request))->filter($builder);
    }
    public function archivar()
    {
        return $reunion->archivado = 1;
    }
}

Reunion.php

    <?php

namespace App;

use App\Filters\ReunionFilter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Reunion extends Model
{
    protected $table = 'reuniones';
    protected $fillable = ['usuario_id', 'cliente_id', 'titulo', 'descripcion', 'estado','archivado'];
    //Una reunión sólo puede pertenecer a un cliente
    public function cliente(){
        return $this->belongsTo(Cliente::class);
    }
    //Una reunión puede tener muchos comentarios
    public function comment(){
        return $this->hasMany(Comment::class);
    }
    //Constructor de filtros para la reunion
    public function scopeFilter(Builder $builder, $request)
    {
        return (new ReunionFilter($request))->filter($builder);
    }
    //Función que de momento no se usa, era para cambiar el valor del campo "archivado" en la tabla reunion
    public function archivar()
    {
        return $reunion->archivado = 1;
    }

    public function nombreCliente(){
        return $cliente->nombre;
    }
}

ReunionController.php

/**
     * Muestra el formulario de edición del producto.
     * @param type $id
     * @return type
     */
    public function edit($id)
    {
        $reunion = Reunion::find($id);
        $archivado = Reunion::select('archivado');
        $clientes = Cliente::select('id','nombre')->where('comercial_id', '=', Auth::user()->id)->get();
        return view($this->view_path.'.edit', compact('reunion','clientes', 'archivado','id'));
    }

View edit meeting, I put the piece of code where gives the failure.

edit.blade.php

<div id="wrapper">
<div class="row">
   <div class="col-md-8 tarjeta">
      <div class="card">
      <div class="card-body" style="padding:30px">
      <form method="post" action="{{action('Empleado\ReunionController@update', $id)}}">
        {{csrf_field()}}
        <input name="_method" type="hidden" value="PATCH">
          <div class="form-group">
            <label for="titulo">Modificar asunto:</label>
            <input type="text" class="form-control" name="titulo" value="{{$reunion->titulo}}">
          </div>
            <div class="form-group">
              <label for="descripcion">Modificar detalles:</label>
              <textarea class="form-control" rows="5" name="descripcion" id="notas">{{$reunion->descripcion}}</textarea>
            </div>
        <div class="form-group">
               <label for="cliente_id">Modificar cliente: </label>
               <select name="cliente_id">
                   <option value="{{$reunion->cliente_id}}" selected hidden>{{$reunion->cliente->nombre}}</option>
                @foreach($clientes as $cliente)
                   <option value="{{$cliente['id']}}">{{$cliente['nombre']}}</option>
                @endforeach
              </select>
        </div>
        <div class="form-group">
               <label for="archivado">Archivado: </label>
               <select name="archivado">
                   <option value="0" @if ($reunion->archivado == '0') selected="selected" @endif>No</option>
                   <option value="1" @if ($reunion->archivado == '1') selected="selected" @endif>Sí</option>
              </select>
        </div>
        <div class="form-group">
              <label >Modificar fecha</label>
              <input type="date" name="date" min="01-01-2018"
                     max="31-12-2100" value="{{$reunion->date}}" class="form-control">
        </div>
        <div class="form-group">
              <label >Modificar hora</label>
              <input type="time" name="time" min="8:00"
                     max="22:00" value="{{$reunion->time}}" class="form-control">
        </div>
            <div class="form-group">
              <label for="estado">Modificar estado:</label>
              <select name="estado">
                <option value="Obra sin empezar" @if ($reunion['estado'] == 'Obra sin empezar') selected="selected" @endif >Obra sin empezar</option>
                <option value="Obra en ejecución" @if ($reunion['estado'] == 'Obra en ejecución') selected="selected" @endif>Obra en ejecución</option>
                <option value="Obra casi terminada" @if ($reunion['estado'] == 'Obra casi terminada') selected="selected" @endif>Obra casi terminada</option>
                <option value="Obra terminada" @if ($reunion['estado'] == 'Obra terminada') selected="selected" @endif>Obra terminada</option> 
              </select>
            </div>
          <div class="form-group" style="text-align: center;">
            <button type="submit" class="btn btn-success">Actualizar reunión</button>
            <br>
            <a href="/empleado/reuniones" class="btn" role="button">Volver a reuniones</a>
          </div>
      </form>
         </div>
      </div>
   </div>
</div>
</div>

EDIT: Code that shows doing dd ($ reunion) as Comrade Pedro says:

Reunion {#281 ▼
  #table: "reuniones"
  #fillable: array:6 [▼
    0 => "usuario_id"
    1 => "cliente_id"
    2 => "titulo"
    3 => "descripcion"
    4 => "estado"
    5 => "archivado"
  ]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▼
    "id" => 5
    "usuario_id" => 5
    "usuario_nombre" => "Ernesto"
    "cliente_id" => 1
    "titulo" => "OE6wpc5GMO8w77v"
    "descripcion" => "r22y5btkPpJXpso4Ixm6IxfDYFGcKcaPoJSIO23gLmH5xL7ZoOd1YUQQQu7L67hFJMiKhUWOACnAYkhK"
    "estado" => "Obra sin empezar"
    "archivado" => 1
    "date" => "2018-07-30"
    "time" => "11:14:00"
    "created_at" => null
    "updated_at" => "2018-07-27 09:34:31"
  ]
  #original: array:12 [▼
    "id" => 5
    "usuario_id" => 5
    "usuario_nombre" => "Ernesto"
    "cliente_id" => 1
    "titulo" => "OE6wpc5GMO8w77v"
    "descripcion" => "r22y5btkPpJXpso4Ixm6IxfDYFGcKcaPoJSIO23gLmH5xL7ZoOd1YUQQQu7L67hFJMiKhUWOACnAYkhK"
    "estado" => "Obra sin empezar"
    "archivado" => 1
    "date" => "2018-07-30"
    "time" => "11:14:00"
    "created_at" => null
    "updated_at" => "2018-07-27 09:34:31"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
    
asked by chewie 27.07.2018 в 08:51
source

1 answer

0

That error means that $reunion is not an object. This can happen because it is null, that is, no meeting with the id that you pass to the function has been found.

    
answered by 27.07.2018 в 08:58