【问题标题】:Laravel 8: Property [name] does not exist on this collection instanceLaravel 8:此集合实例上不存在属性 [名称]
【发布时间】:2021-07-02 04:10:25
【问题描述】:

我正在使用 Laravel 8 开发我的项目,在这个项目中,我有一个名为 hostings 的表,它的迁移在这里:

public function up()
    {
        Schema::create('hostings', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

现在我想从数据库返回一些结果并在刀片上显示它们,所以我添加了这个:

<table>
    <tr>
        <th>Hosting Name:</th>
        <td>{{ $hosting->name }}</td>
    </tr>
</table>

但现在我得到了这个错误:

Property [name] does not exist on this collection instance

那么这里出了什么问题?我该如何解决这个问题?

如果您与我分享任何想法或建议,我将不胜感激,

提前致谢。

控制器代码:

public function index()
    {
        $hosting = Hosting::all();
        return view('admin.index', compact('hosting'));
    }

【问题讨论】:

  • 请分享控制器代码
  • @OMR 抱歉,我刚刚添加了它
  • Hosting::all 返回用于循环遍历每个项目的数组。
  • collection instance 这意味着你有很多行需要循环以获得单个值
  • 如果托管中只有一个值,则使用“first”而不是“all”

标签: php laravel laravel-8


【解决方案1】:

因为你有收藏,你需要循环它来获得价值

<table>
    <tr>
        @foreach ($hosting as $host)
        <th>Hosting Name:</th>
        <td>{{ $host->name }}</td>
        @endforeach
    </tr>
</table>

否则你可以用逗号分隔所有主机名

<table>
    <tr>
        <th>Hosting Name:</th>
        <td>{{ $hosting->pluck('name')->join(',') }}</td>
    </tr>
</table>

或者你可以像这样获取第一个收集数据

<table>
    <tr>
        <th>Hosting Name:</th>
        <td>{{ $hosting->first()->name }}</td>
    </tr>
</table>

参考 链接https://laravel.com/docs/8.x/collections#method-pluck

https://laravel.com/docs/8.x/collections#method-join

【讨论】:

    【解决方案2】:

    试试这个:

    <table>
    <tr>
       @foreach($hosting as $h)
        <th>Hosting Name:</th>
        <td>{{ $h->name }}</td>
       @endforeach
    </tr>
    

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2020-07-11
      相关资源
      最近更新 更多