problem with relations, does not find properties

Viewed 194

i have a problem with relations, does not find properties,

Error: Trying to get property 'servicio' of non-object

Controller:

 public function index(Request $personal){


    $personal = Personal::where('nombre' , $personal)->with('nombre')->get();
    $servicios = \App\Models\Eventos::orderByDesc('hora')->get();



    return view('personal', compact('servicios','personal'));

   
  }

Model Servicios:

    class Servicios extends Model
{
    use HasFactory;

    public function eventos()
    {
        return $this->belongsTo(Evento::class);
    }

    public function personal()
    {
        return $this->belongsTo(Personal::class);
    }
}

Model Eventos:

 class Eventos extends Model
{
    protected $table= 'eventos';

    //
    protected $fillable = [
        'titulo', 'descripcion', 'fecha', 'hora', 'prioridad', 'servicio', 'personal',
    ];

    public $timestamps = false;

    public function servicio()
    {
        return $this->belongsTo(Servicios::class);
    }
    public function personal()
    {
        return $this->belongsTo(Personal::class);
    }

In blade.php:

@foreach ($servicios as $hoy)
  <td>{{$hoy->servicio_id->servicio}}</td>
  @endforeach

Database:

https://i.imgur.com/LvjR6qS.png

I do not understand the error so that I do not find the property

1 Answers

In Laravel you can access relationships on the function name accessed as a property.

The following should fix your problem. Having relationship fillable does nothing.

@foreach ($servicios as $hoy)
    <td>{{ $hoy->servicio->servicio_property_to_access }}</td>
@endforeach

Update

You have a servicio field on your model if i remember correctly that can conflict renaming the relationship might help.

class Eventos extends Model
{
    public function servicioRelationship()
    {
        return $this->belongsTo(Servicios::class);
    }

@foreach ($servicios as $hoy)
    <td>{{ $hoy->servicioRelationship->servicio }}</td>
@endforeach
Related