Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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. :)

like image 526
bawsi Avatar asked Dec 04 '16 11:12

bawsi


People also ask

What is difference in first and get Laravel?

The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What is -> in Laravel?

-> and => are both operators. The difference is that => is the assign operator that is used while creating an array. For example: array(key => value, key2 => value2) And -> is the access operator. It accesses an object's value.

What is first () in eloquent?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.

What is difference between GET and all in Laravel?

all() is a static method on the Eloquent\Model . All it does is create a new query object and call get() on it. With all() , you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.


1 Answers

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

first() will return element itself.

like image 50
Alexey Mezenin Avatar answered Oct 21 '22 15:10

Alexey Mezenin