How to Retrieve Data Using Laravel Eloquent?

Eloquent is a very interesting concept in Laravel. It is Laravel’s flagship database tool out of the box which is built using Laravel Query builder. It is easy to understand and use for any developer. Basically Eloquent is an “ActiveRecord” ORM, which means it is a single abstraction layer to deal with multiple types of databases. It means Eloquent doesn’t case which type of databases you are using or how many are there. It’s implementation is simple and consistent with all of them. There are many ways to retrieve data using Laravel eloquent. First of all we can get all records using all() method.

$contacts = Contact::all();

We can also use filters like where.

$vips = Contact::where( 'vip', true )->get();

Let’s use orderBy(). This is the query to get 10 latest records.

$latestContacts = Contact::orderBy( 'created_at', 'desc' )->take( 10 )->get();

Now if we want only one record from query then we can use first() method. Let’s replace get() with first().

$latestContacts = Contact::orderBy( 'created_at', 'desc' )->take( 10 )->first();

Now it will just return last record from that array which we get if we use get() method. Another method will be find().

$contact = Contact::find( 100 );

There is another method findOrFail().

$contact = Contact::findOrFail( 100 );

The difference is, if record will not be found or doesn’t exist then find() will return null but findOrFail() will throw 404 exception. In the very same way, firstOrFail() method will throw an exception as well.

$contact = Contact::where( 'vip', true )->firstOrFail();

Now  if you want to catch exception then you catch ModelNotFound exception.

try {
    $contact = Contact::findOrFail( $id );
} catch ( ModelNotFoundException $e ) {
    echo $e->getMessage();

There is a very interesting Laravel method called chunk() method which retrieve specific number of records and do operations on them chunk by chunk. It is very useful when we deal with larger tables having hundreds of records.

Contact::chunk( 10, function ( $contacts ) {
    foreach ($contacts as $contact){
	$contact->vip = true;
} );

I hope now you can retrieve data using Laravel eloquent. If you have any questions please leave a comment. We really appreciate that.