【问题标题】:Laravel 5.2 Trying to get property of non-objectLaravel 5.2 试图获取非对象的属性
【发布时间】:2018-01-15 06:55:35
【问题描述】:

我正在按照教程在 laravel 5.2 上制作博客项目,我试图从其他表(用户表)中显示用户名。帖子属性在视图中成功显示,但是当我尝试从使用表访问属性时,我得到了 Trying to get property of non-object。

这是我的看法:

 <div class="blog-post">
            <h2 class="blog-post-title">
            <a href="/posts/{{$post->id}}">
            {{ $post->title }}
            </a>
            </h2>
            <p class="blog-post-meta">
            {{ $post->user->name }}
            {{ $post->created_at->toFormattedDateString() }}
            </p>

            {{ $post->body }}

          </div><!-- /.blog-post -->

这是我的帖子控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\User;

use App\Http\Requests;



class PostsController extends Controller
{
    //
  public function __construct(){
    $this->middleware('auth')->except(['index','show']);
  }

    public function index(){


        $posts = Post::latest()->get();
        return view('posts.index',compact('posts'));
    }

    public function show($id){

        $post = Post::find($id);
        return view('posts.show',compact('post'));
    }

    public function create(){
        return view('posts.create');
    }

   public function store(){
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required'

        ]);

    Post::create([
      'title' => request('title'),
      'body' => request('body'),
      'user_id' => auth()->id()
      ]);


    // $post = new Post;
    // $post->user_id = auth()->id()
    // $post->title = request('title');
    // $post->body = request('body');


    // $post->save();

    return redirect('/');

   }
}

这是帖子模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
    protected $fillable = ['title','body','user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments(){
        return $this->hasMany(Comment::class);
    }



}

用户模型:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts(){
        return $this->hasMany(Post::class);
    }
}

【问题讨论】:

  • dd($post-&gt;user) 的结果是什么?
  • 结果是:User {#179 ▼ #fillable: array:3 [▶] #hidden: array:2 [▶] #connection: null #table: null #primaryKey: "id" # keyType: "int" #perPage: 15 +incrementing: true +timestamps: true #attributes: array:7 [▶] #original: array:7 [▶] #relations: [] #visible: [] #appends: [] #guarded: array:1 [▶] #dates: [] #dateFormat: null #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: true +wasRecentlyCreated: false }
  • 错误在这一行{{ $post-&gt;user-&gt;name }}?还是指向另一条线?
  • 你试过在视图中使用$post-&gt;created_at而不是$post-&gt;created_at-&gt;toFormattedDateString()
  • 这能回答你的问题吗? Trying to get property of non-object - Laravel 5

标签: php laravel laravel-5.2


【解决方案1】:

正如您所说,您在通过post 访问user 的属性时遇到此错误。这意味着您的$post-&gt;usernull 或者它不是object 而是array(可能性较小)。

更高的可能性是null 问题。你检查过吗?我希望您使用{{$post-&gt;user-&gt;name ?? ''}}(仅在 php 7 中支持)同时在视图中显示用户名。这意味着如果 $post-&gt;user-&gt;name 未设置,则不显示任何内容。

检查$post-&gt;user 是否为null。如果任何postnull,那么问题是,为什么$post-&gt;user 可以是null?可能的原因是什么?

$post-&gt;user 为空的可能原因是:

  1. 未正确建立关系。确保您的 posts 表有一个 user_id 列,因为您的关系已定义。
  2. posts 表中,user_id 可以为空,对于该特定帖子,user_id 为空。
  3. 该帖子的user_id 链接到一个不存在的user。这可以使用外部约束来限制。

【讨论】:

    猜你喜欢
    • 2016-12-23
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2015-09-22
    相关资源
    最近更新 更多