属性 [costo] 在此集合实例上不存在

Property [costo] does not exist on this collection instance

我需要打印服务的价格,但找不到包含价格的列。 也许我在人际关系上做错了什么,但我自己想不通

数据库:

控制器:

  public function details(Request $request,$id){

    $datax = [
      'category_name' => 'apps',
      'page_name' => 'calendar',
      'has_scrollspy' => 0,
      'scrollspy_offset' => '',

  ];



  
    $evento = Eventos::find($id);
    $servicio = \App\Models\Eventos::select("servicio_id")->where('servicio_id', $evento->id)->get('servicio_id');
    $event = Eventos::find($id);
    $event->asistencia = $request->asistencia;
    $event->cancelado = $request->cancelado;
    $event->save();

    return view("evento",[
      "event" => $event,
      "servicio" => $servicio
    ])->with($datax);

  }

blade.php

  <div class="input-group mb-4">
  <div class="input-group-prepend">
    <span class="input-group-text">$</span>
  </div>
  <input type="text" value="{{$servicio->costo}}" class="form-control col-md-3" aria-label="Amount (to the nearest dollar)">
  <div class="input-group-append">
    <span class="input-group-text"></span>
  </div>
</div>

我需要打印与 service_id

有关的“costo”列

求助

您可以使用 laravel 雄辩的一对一关系。 如果您在 App/Models 中有这两个 Servicio.phpEvento.php 或者您的模型名称是什么,请仅在下面的代码中替换您的模型,执行此操作:

1-App/Models/Servicio.php 中定义此关系:

 public function evento()
    {
        return $this->hasOne(Evento::class);
    }

App/Models/Evento.php中定义这个关系:

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

现在在控制器中添加:

$evento = Eventos::where('id' , $id)->with('servicio')->first();

在blade中使用这个:

  <input type="text" value="{{$evento->servicio->costo}}" >

2- 你也可以这样做,但我建议你第一个: 仅在您的代码中更改此内容: $servicio = \App\Models\Servicio::where('id', $evento->servicio_id)->first();