Home > Net >  Attempt to read property "id" on null - show.blade.php
Attempt to read property "id" on null - show.blade.php

Time:08-16

I don't understand at all why I have this mistake: Attempt to read property "id" on null (View: C:\xampp\htdocs\resources\views\admin\employees\show.blade.php)

show.blade.php

'Category' => '<a href="'. route('admin.employee-categories.show', $model->category->id) . '">' . $model->category->name . '</a>',

Model Empolyee

    public function category(): BelongsTo
    {
        return $this->belongsTo(EmployeeCategory::class, 'category_id');
    }

I try:

'Category' => '<a href="'. route('admin.employee-categories.show', $model->category ? $model->category->id: '') . '">' . $model->category ? $model->category->name : ' ' . '</a>',

But then I have mistake - Attempt to read property "name" on null (View: C:\xampp\htdocs\resources\views\admin\employees\show.blade.php)

UPD:

In index.blade.php I SoftDelete one Employee.

Then I go to index.blade.php for EmployeeCertificates.

But then I should to see that Employee was deleted.

But I have Attempt to read property "name" on null (View: C:\xampp\htdocs\resources\views\components\data-table.blade.php)

EmployeeCertificates index.blade.php:

                       [
                            'attribute' => function($item) { return $item->employee->name; },
                            'label' => 'Сотрудник',
                            'style' => 'width: 30%; min-width: 200px;',
                            'filter' => [
                                'class' => \App\View\Components\Filters\Select::class,
                                'params' => [
                                    'name' => 'employee_id',
                                    'options' => $employees->pluck('name', 'id')->toArray(),
                                    'value' => request()->get('employee_id', ''),
                                    'htmlAttributes' => '',
                                ],
                            ],
                        ],

Employee model:

    public function certificates(): HasMany
    {
        return $this->hasMany(EmployeeCertificate::class, 'employee_id');
    }

CodePudding user response:

have you tried this?

'Category' => '<a href="'. route('admin.employee-categories.show', $model->category?->id) . '">' . $model->category?->name . '</a>',

CodePudding user response:

Any time you have two arrows, you have to think defensively. What if the relation is missing?

$item->employee->name; 

What if $item does not have an employee? An error will be thrown since employee will be null, and you cannot get name from null

In many cases like this, using the null coalesce operator (> php 7.4) you can provide a fallback value if there is a null present in the referenced objects

$item->employee->name ?? 'no employee'; 

if $item does not have an employee relation then 'no employee' will be printed instead

  • Related