Home > Back-end >  Laravel, Eloquent, array when I need just a value
Laravel, Eloquent, array when I need just a value

Time:03-14

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.

CodePudding user response:

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

CodePudding user response:

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).

  • Related