Skip to content
Advertisement

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

In table in view with data from products table I am traying to show names from user table but getting this error. I made Laravel relations in models and foreign keys. And added directory in product controller for user model.

Error: Trying to get property ‘name’ of non-object (View: /home/laravel/web/laravel.swt101.eu/public_html/abonamenty/resources/views/products/index.blade.php)

This is part of my controller for showing product data:

  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);
    }

This is part of view where I am getting this error

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

This is rest code of this view:

@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

This is my product model:

    <?php


namespace App;

use KyslikColumnSortableSortable;
use IlluminateDatabaseEloquentModel;


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('AppUser','user_id');
    }
            
    
}

This is my user model:

<?php
  
namespace App;
  
use IlluminateNotificationsNotifiable;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use SpatiePermissionTraitsHasRoles;
use KyslikColumnSortableSortable;
use IlluminateDatabaseEloquentModel;

  
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('AppProduct');
    }
        public function invoices()
    {
        return $this->hasMany('AppInvoice');
    }
}

Advertisement

Answer

The error indicates that $product->user is probably returning null. Maybe not all products are associated with users for some reason.

Find the product id and look it up in the database, to see if it has a user connected.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement