【发布时间】: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->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->user->name }}?还是指向另一条线? -
你试过在视图中使用
$post->created_at而不是$post->created_at->toFormattedDateString()
标签: php laravel laravel-5.2