2017-08-04 54 views
1

我有一个列ID表,和三个文本字段和型号名称是邮政为什么雄辩财产不存在于此收集实例?

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('title', 256); 
     $table->string('slug', 256); 
     $table->text('body'); 
     $table->timestamps(); 
    }); 
} 

虽然从该表中获取数据,并从控制器和视图返回雄辩对象<p>{{$post}}</p>,这很好,但在访问财产标题为<p>{{$post->title}}</p>这是一个错误

class BlogController extends Controller 
{ 
    public function single($slug){ 
     $post = Post::where('slug', '=', $slug)->get(); 
     //return $post; 
     return view('posts.single')->withPost($post); 
    } 
} 

错误:

Property [title] does not exist on this collection instance 
+0

'$ POST'是一个集合,不是一个单一的'邮政'。 – tkausl

回答

0

你应该得到的第一个元素不是集合:

public function single($slug){ 
    $post = Post::where('slug', '=', $slug)->first(); 
    //return $post; 
    return view('posts.single')->withPost($post); 
} 

Because get will always return a collection even if your query could only ever return a single row and first returns a single model instance

+0

@Jobayer Ithink在你的移植中,你的意思是'$ table-> string('slug',256);'不是'title'在第二行! – Maraboc

+0

:D你说得对,我刚刚编辑过。 –

+0

它工作吗? – Maraboc