消息“试图获取非对象的属性'subo_name'时引发ErrorException

时间:2019-07-31 19:39:13

标签: laravel

错误消息抛出

  

“试图获取非对象的属性'subo_name'(查看:   C:\ xampp \ htdocs \ org \ resources \ views \ users \ index.blade.php)“

主要模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Maino extends Model
{
    protected $fillable = [
        'maino_name'
    ];


     public function subo()
    {
        return $this->hasMany('App\Subo');
    }
}

Sub 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subo extends Model
{   

    protected $fillable = [
        'subo_name','maino_id'
    ];

    public function maino()
    {   

        return $this->belongsTo('App\Maino');
    }

    public function users()
    {
        return $this->hasMany('App\User');
    }

}

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','role_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 function role()
     {
        return $this->belongsTo('App\Role');
     }


     public function profile()
     {
        return $this->hasMany('App\Profileinfo');
     }

     public function suborg()
     {
        return $this->belongsTo('App\Subo');
     }
}

UserController 代码

public function index()
{  
  // $user=User::all();
     $users=User::all();
     return view('users.index',compact('users'));
}

index.blade.php

    @extends('mainorg.main')
    @section('title','Users')
    @section('content')
    <!-- DataTables Example -->
            @if(Session::has('status'))
                <div class="alert alert-success">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span></button>
                    {{ Session::get('status') }}
                </div>
      @endif
            <div class="card mb-3">

              <div class="card-header">
                <!-- <i class="fas fa-table"></i>
               MainOrg  --><div class="container"><a href="{{URL::asset('users/create')}}"><button class="btn btn-primary float-right">Add SubOrg</button></a></div></div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                      <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>user</th>
                        <th>main org</th>
                        <th>suborg</th>
                        <th>Edit</th>
                        <th>Delete</th>
                      </tr>
                    </thead>
                    <tfoot>
                      <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>user</th>
                        <th>main org</th>
                        <th>suborg</th>
                        <th>Edit</th>
                        <th>Delete</th>
                      </tr>
                    </tfoot>
                    @foreach($users as $user)
                    <tr>
                        <td>{{$user->id}}</td>
                        <td>{{$user->name}}</td>
                        <td>{{$user->role->role_name}}</td>

                        <td>{{$user->suborg->subo_name}}</td>
                        <td><a href="{{ route('users.edit',$user->id) }}" class="btn btn-success">Edit</a></td>
                        <td><form action="{{route('users.destroy',$user->id)}}" method="post">
            @method('DELETE')
            @csrf
            <input type="submit" name="" value="DELETE" class="btn btn-danger">
          </form></td>

                      </tr>
                      @endforeach

                    <tbody>

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          @endsection

我正面临与此代码有关的问题,请帮助我解决此问题...............................

2 个答案:

答案 0 :(得分:1)

该错误表示您的$users中的一个在循环时没有suborg。因此{{ $user->suborg }}null,因此您无法访问->name中的null。要解决此问题,请将您的用户限制为仅拥有suborg的用户,或者在循环时检查:

public function index() {  
  $users=User::with('suborg')->has('suborg')->get();
  return view('users.index',compact('users'));
}

注意:您可以在单个查询中同时使用withhas;他们做不同的事情。

或者,在循环用户时,检查是否存在:

@foreach($users as $user)
<tr>
  <td>
  @if($user->suborg)
  {{ $user->suborg->subo_name }}
  @else
  No Suborg
  @endif
  </td>
</tr>
@endforeach

答案 1 :(得分:0)

在两个或多个模型之间创建关系时,应在雄辩的调用中使用with在模型使用过程中使用关系方法,并且还可以在要传递多个像-with(['suborg', 'example'])时编写。在索引方法中,下面的$users变量make dd($users)并检查是否有任何关系数据。如果我认为可以找到,那应该可以。

public function index()
{  
  // $user=User::all();
     $users=User::with('suborg')->get();
     return view('users.index',compact('users'));
 }

还有您的index.blade.php

@foreach($users as $user)
     <tr>
         <td>{{$user->id}}</td>
         <td>{{$user->name}}</td>
         <td>{{$user->role->role_name}}</td>
         <td>{{$user->suborg->subo_name || 'Not Found'}}</td>
         ......
@endforeach