How to make code shorter with QueryBuilder in Laravel

Categorized as Laravel

Imagine, we need to get the name of the first admin in our web application. We can do that in two ways:

The first way, using four lines of code, and if the user is not present, it will throw an error:

User::where('type', UserTypeEnum::ADMIN)
    ->select(['name'])
    ->first()
    ->name;

The second way uses only 2 lines of code, and if the user is not present, it will return null:

User::where('type', UserTypeEnum::ADMIN)
    ->value('name');

Enjoy!

via @Laratips1

Leave a reply

Your email address will not be published.