试图获取非对象的属性“名称”(视图:(...)资源/视图/产品/index.blade.php)

Posted

技术标签:

【中文标题】试图获取非对象的属性“名称”(视图:(...)资源/视图/产品/index.blade.php)【英文标题】:Trying to get property 'name' of non-object (View: (...) resources/views/products/index.blade.php) 【发布时间】:2020-11-16 16:50:15 【问题描述】:

在包含产品表数据的视图中,我正在托盘显示用户表中的名称,但出现此错误。我在模型和外键中建立了 Laravel 关系。并在产品控制器中为用户模型添加了目录。

错误:试图获取非对象的属性“名称”(查看:/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 >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-&gt;user里面有什么吗?我认为用户没有被检索到 【参考方案1】:

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

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

【讨论】:

以上是关于试图获取非对象的属性“名称”(视图:(...)资源/视图/产品/index.blade.php)的主要内容,如果未能解决你的问题,请参考以下文章

Blade - 试图获取非对象的属性

试图从模型获取数据到视图,我得到这些错误: 试图获取非对象和未定义变量的属性

试图获取非对象的属性

试图在 laravel eloquent 中获取非对象错误的属性“名称”

Laravel:ErrorException(E_ERROR)试图获取非对象的属性(视图:..../show.blade.php)[关闭]

Laravel - 试图在集合上获取非对象的属性