Home » Php » Laravel first() vs take(1)->get()

Laravel first() vs take(1)->get()

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m learning laravel, and am kind of following a youtube tutorial where were building a blog. Anyway, I am trying to make a page which shows single blog post, and uses slug instead of id to show it. Anyway, this is my blog controller:

class BlogController extends Controller {

    public function getSingle($slug) {
        $post = Post::where('slug', $slug)->take(1)->get();
        return view('blog/single')->with('post', $post);
    }
}

But this way, It wont work.. On my blog/single view, i cant access $post->title for example. But, when I do it like this:

class BlogController extends Controller {

    public function getSingle($slug) {
        $post = Post::where('slug', $slug)->first();
        return view('blog/single')->with('post', $post);
    }
}

.. it works fine. I have access to title, body and created/updated at times.

What is the reason first method wont work?

Thank you in advance. 🙂

Answers:

It’s because take(1)->get() will return a collection with one element.

first() will return element itself.