To retrieve a single record by its primary key using Eloquent in Laravel, you can use the find()
method. Here's how you can do it:
User
model, you can use the following code:use App\Models\User;
find()
method on the model with the primary key of the record you want to retrieve. For example, if the primary key column is id
and you want to retrieve the record with the id of 1, use the following code:$user = User::find(1);
find()
method will return the record if it exists or null
if it does not. You can then use the $user
variable to access the retrieved record and its properties. For example, if the User
model has a name
column, you can retrieve it like this:if ($user) {
echo $user->name;
} else {
echo 'User not found';
}
By using the find()
method, you can easily retrieve a single record by its primary key in Laravel using Eloquent.