How to query single record in Laravel Eloquent

The get() method in laravel eloquent will return more than one records, which is good if you really want to do that, but what if you only need one record, how to query a single record in laravel eloquent?

First of all you can't use the get() method, if what you want is just returning a single record, the get() method is not a good choice.

Instead of using the get() method, use the first() method if you want to retrieve a single record/ single value/ row.

Eloquent get() method
$users = User::get();

Eloquent first() method
$user = User::first();
$user = User::where('user_id', '=', 2)->first();
The first() method will return only one records, even if there are more than one records in the table that match the query, the first one will be returned.

No comments :

Post a Comment

Leave A Comment...