Php 为什么此集合实例上不存在Elounce属性?
我有一个列ID为的表,三个文本字段,模型名为PostPhp 为什么此集合实例上不存在Elounce属性?,php,laravel-5,Php,Laravel 5,我有一个列ID为的表,三个文本字段,模型名为Post public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title', 256); $table->string('slug', 256); $table->text(
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();
});
}
当从这个表中获取数据并从控制器返回雄辩的对象并作为{{$post}
查看时,这很好,但是当作为{{$post->title}
访问属性标题时,会出现错误
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
您应该获取第一个元素,而不是集合:
public function single($slug){
$post = Post::where('slug', '=', $slug)->first();
//return $post;
return view('posts.single')->withPost($post);
}
因为
get
将始终返回集合,即使您的查询可以
仅返回一行,first
返回一个模型实例
$post
是一个集合,而不是单个的post
@Jobayer我想在您的迁移中您指的是$table->string('slug',256)代码>不是第二行的标题
!!相信我,如果你只是解释一下,为什么上一个不起作用,而是->first(),我会竖起大拇指的
正在工作:)因为get
将始终返回集合,即使您的查询只能返回一行,first
返回一个模型实例;)