试图获得 属性 'name' 的非对象(视图:(...) resources/views/products/index.blade.php)

Trying to get property 'name' of non-object (View: (...) resources/views/products/index.blade.php)

在 table 中查看来自产品 table 的数据,我正在尝试显示用户 table 的名称,但出现此错误。我在模型和外键中建立了 Laravel 关系。并在产品控制器中为用户模型添加了目录。

错误:试图获取非对象的 属性 'name'(视图:/home/laravel/web/laravel.swt101.eu/public_html/abonamenty/resources/views/products/index.blade.php)

这是我用于显示产品数据的控制器的一部分:

  public function index()
    {
        $user = User::all('name','id');        
        $products = Product::sortable()->paginate(5);
        return view('products.index',compact('products', 'user'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

这是我收到此错误的视图的一部分

 <td>{{ $product->user->name }}</td>

这是该视图的剩余代码:

@extends('layouts.app')


@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Zarządzanie abonamentami</h2>
            </div>
            
<div class="col-md-4">
<form action="/search2" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
            <div class="pull-right">
                @can('product-create')
                <a class="btn btn-success" href="{{ route('products.create') }}"> Utwórz nowy abonament</a>
                @endcan
            </div>
        </div>
    </div>


    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif


    <table class="table table-bordered">
        <tr>

            <th scope="col">@sortablelink('id', 'Numer')</th>
            <th scope="col">@sortablelink('name', 'Nazwa usługi')</th>
            <th scope="col">@sortablelink('user_id', 'Kontrachent')</th>
            <th scope="col">@sortablelink('category', 'Kategoria')</th>
            <th scope="col">@sortablelink('launchdate', 'Data uruchomienia')</th>
            <th scope="col">@sortablelink('expirationdate', 'Data wygasnięcia')</th>
            <th scope="col">@sortablelink('renewalprice', 'Cena odnowienia')</th>
            <th width="280px">Akcja</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->user->name }}</td>
            <td>{{ $product->category }}</td>
            <td>{{ $product->launchdate }}</td>
            <td>{{ $product->expirationdate }}</td>
            <td>{{ $product->renewalprice }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id) }}" method="POST">
                    <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Więcej</a>
                    @can('product-edit')
                    <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edytu</a>
                    @endcan


                    @csrf
                    @method('DELETE')
                    @can('product-delete')
                    <button type="submit" class="btn btn-danger">Usuń</button>
                    @endcan
                </form>
            </td>
        </tr>
        @endforeach
    </table>

{!! $products ?? ''->appends(request()->except('page'))->render() !!}
 



@endsection

这是我的产品型号:

    <?php


namespace App;

use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;


class Product extends Model
{
    /**
     * The attributes that are mass assignable.
     *  
     * @var array
     */
    use Sortable;
    
    
    protected $fillable = [
        'name', 'detail', 'id', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'user_id', 'billingperiod', 'internalcost', 'status'
    ];
    
    public $sortable = ['id', 'name', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'category', 'user_id'];
    
    public function user()
    {
      return $this->belongsTo('App\User','user_id');
    }
            
    
}

这是我的用户模型:

<?php
  
namespace App;
  
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;

  
class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;
    use Sortable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'surname', 'showname', 'business', 'NIP', 'PESEL', 'address', 'city', 'postalcode', 'phone', 'comments', 
    ];
    public $primaryKey = 'id';
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    
    public $sortable = ['name',
                        'email',
                         'surname', 
                        'showname', 
                        'business',
                        'address',
                        'city',
                        'phone',
                        'role',
                       ];
    
        public function products()
    {
        return $this->hasMany('App\Product');
    }
        public function invoices()
    {
        return $this->hasMany('App\Invoice');
    }
}

错误表明 $product->user 可能正在返回 null。也许由于某种原因,并非所有产品都与用户相关联。

找到产品 ID 并在数据库中查找它是否有连接的用户。