访问 collection laravel

get access to collection laravel

我是 laravel 框架的新手,在 3 个模型上工作 顾客, 事故, 执照 其中关系如下:

public  function License()
        {
            return $this->hasOne(license::class,'driver_id');
        }

    public function cars()
        {
            return $this->hasMany(car::class);
        }

在控制器中我是这样的:

public function AdminCustomers()
    {
        $customers = Customer::with('cars')->with('License')->get();
        return view('admin.AdminCustomers',compact('customers'));
    }

现在我想在 view.blade 页面上显示所有 3 个模型的数据

<tbody>
                    @foreach($customers as $customer)

                                    <tr>
                                        <td>{{$customer->id}}</td>
                                        <td>{{$customer->name}}</td>
                                        <td>{{$customer->adderss}}</td>
                                        <td>{{$customer->mobileNo}}</td>
                                        <th>{{$customer->License->id}}</th>
                                        <th>{{$customer->License->Exp}}</th>
                                        <td>{{$customer->cars->id}}</td>
                                        <td>{{$customer->cars->color}}</td>
                                        <td>{{$customer->cars->model_no}}</td>
                                        <td>{{$customer->cars->company}}</td>
                                    </tr>
                               
                    @endforeach
                    </tbody>

但是不行,不知道问题出在哪里 错误异常

Property [id] does not exist on this collection instance.

检查数据库中对应的table中的名称,如果它与“id”不同,则将其指定到模型中,如

protected $primaryKey = 'xxx';

$customer->cars 将 return 一个集合,因为关系是 hasMany,所以您需要在视图中遍历集合

@foreach($customers as $customer)

    <tr>
        <td>{{$customer->id}}</td>
        <td>{{$customer->name}}</td>
        <td>{{$customer->adderss}}</td>
        <td>{{$customer->mobileNo}}</td>
        <th>{{$customer->License->id}}</th>
        <th>{{$customer->License->Exp}}</th>
            @foreach($customer->cars as $car)
                <td>{{$car->id}}</td>
                <td>{{$car->color}}</td>
                <td>{{$car->model_no}}</td>
                <td>{{$car->company}}</td>
            @endforeach
    </tr>
                               
@endforeach