首页 > 解决方案 > 试图在 Laravel 脚本中获取非对象的属性“服务”

问题描述

我安装了一个 Laravel,现在我想从一个站点 api 使用并在我的站点中查看它的服务,但是当我打开“API SERVICES PAGE”时,出现了这个错误:

“试图获取非对象的属性‘服务’(查看:/home/core/resources/views/admin/apiServices.blade.php)”

对于这一行:

 <td>{{ isset($item->service->id) ? $item->service->id : $item->service}}</td>

我的页面代码:

    <div class="row">
        <div class="col-md-12">
            <div class="tile">
                <h3 class="tile-title">API Services List</h3>
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>Serial</th>
                        <th>Service ID</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Min</th>
                        <th>Max</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($items as $key => $item)
                        <tr>
                            <td>{{ (int) $key+1 }}</td>
                            <td>{{ isset($item->service->id) ? $item->service->id : $item->service}}</td>
                            <td>{{ $item->name }}</td>
                            <td>{{ $item->category }}</td>
                            <td>{{ isset($item->rate) ? $item->rate : $item->price_per_k }} $</td>
                            <td>{{ $item->min }}</td>
                            <td>{{ $item->max }}</td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

及其控制器的一部分:

public function apiService(){
        $api = ApiSetting::first();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api->url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,
            "api_tokens=".$api->key."&action=services");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec ($ch);
        curl_close ($ch);
        $items = json_decode($server_output);
        return view('admin.apiServices', compact('items'));
    }

标签: phphtmllaravel

解决方案


您的问题中没有足够的信息。

在我看来,您正在尝试访问关系对象而不在模型中设置关系。

我不知道您想如何从项目访问服务,但您可能希望在您的项目模型中使用类似的东西

public function Service() 
{
    return $this->hasmany('App\Service');
}

请参考: https ://laravel.com/docs/5.7/eloquent-relationships


推荐阅读