私はlaravel 5.2でブログプロジェクトを作成するためにチュートリアルに従っています。私は他のテーブル(ユーザーテーブル)からユーザー名を表示しようとしています。投稿のプロパティはビューに正常に表示されますが、私はuseテーブルからプロパティにアクセスしようとすると、非オブジェクトのプロパティを取得しようとしています。ここでLaravel 5.2非オブジェクトのプロパティを取得しようとしています
が私の見解です:
<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 -->
、ここでは私のPostsControllerのです:
<?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\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\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)'の結果は何ですか? – Laerte
結果は:ユーザー{#179▼ #fillable:アレイ:3 [▶] #hidden:アレイ:2 [▶] #connection:ヌル #table:ヌル #primaryKey: "ID" #keyType "INT" #perPage:15 +インクリメント:真 +タイムスタンプ:真 #attributes:配列:7 [▶] #original:配列:7 [▶] #relations:[] #visible:[ ] #appends:[] #guarded:配列:1 [▶] #dates:[] #dateFormat:ヌル #casts:[] #touches:[] #observables:[] #with:[] #morphClass:+ ヌルが存在する:真 + wasRecentlyCreated:偽 } – Ahmed
エラーがこの行にある '{{$ポスト> USER->名}}' ?または別の行を指していますか? – Laerte