Jobayer sheikh
Jobayer sheikh

Reputation: 13

Why eloquent property does not exist on this collection instance?

I have a table with column ID, and three text field and the model name is Post

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();
    });
}

While getting data from this table and return the eloquent object from controller and view as <p>{{$post}}</p>, it's fine but while accessing the property title as <p>{{$post->title}}</p> it's puts an error.

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

Error:

Property [title] does not exist on this collection instance

Upvotes: 1

Views: 4989

Answers (1)

Maraboc
Maraboc

Reputation: 11083

You should get the first element not the collection :

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

Upvotes: 2

Related Questions