1

It may be a simple thing, but cant figure it out without making more complicated if/else statement which I believe is not needed.

I need to retrieve name of user with specified id number. But there is a chance, that user with given id doesnt exist.

With such code: $author = User::select('name')->where('id', $givenId)->firstOr( function () { return 'Gone'; });

and it works almost fine, but if user exists, Im getting an array {"name":"User"} as a result. Cant just write ->value('name') at the end cause when user doesnt exists it gives me an error that I run method value on a null object.

2 Answers 2

1

You can just call value directly on the Builder to return the value of a single column:

User::where('id', $givenId)->value('name') ?? 'Gone';

This is assuming users have a name that isn't null (or null equivalent).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. As always Im searching for too complicated solution when it comes that easy when you already see it...
0

Ternary operators are great for the if else short solutions for variables, And using the optional helper will avoid the not set issues

$author = optional(User::select('name')
    ->where('id', $givenId)
    ->firstOrFail())->name ?? 'Gone';

Otherwise just using the optional works great. e.g.

$author = optional(User::select('name')
    ->where('id', $givenId)
    ->firstOrFail())->name

Then in the template

@if ($auther)
  {{ $author }}
@endif

1 Comment

->firstOrFail give an error 404 page what I dont want. If I use just ->first() method, then optional method doesnt work - it needs both arguments - strings, not a null like in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.