2017-08-04 56 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