In some cases we want to get Eloquent model single column value based on other column value. Let’s assume we have user id and we want to get his e-mail only.
We can obviously do:
1 2 |
$user = User::find($id); $email = $user->email; |
or even shorter:
1 |
$email = User::find($id)->email; |
but there is one big problem with this – what if user doesn’t exist? Obviously we fail in such case and this is what we might not want to achieve.
In many cases we would like to either get email of user (if he exists) or get null if user doesn’t exist.
How can we handle this easily?
Obviously we can add simple condition like this:
1 2 |
$user = User::find($id); $email = $user ? $user->email : null; |
or again we can do it a bit shorter like this:
1 |
$email = ($user = User::find($id)) ? $user->email : null; |
but fortunately we don’t have to do this using Laravel.
Not so many Laravel developers are aware of value
method that can use for this.
For example if we want to have e-mail of user and want to get this user id we can use this like this:
1 |
$id = User::where('email', $email)->value('id'); |
Going back to what we want to achieve (get email) when having user, we can use it like so:
1 |
$email = User::where('id', $id)->value('email'); |
so either we get e-mail of existing user or null in case there’s no user with such email.
But if you look a bit closer, there’s one drawback of this. We need to use model key here in explicit way, what could be sometimes a bit more problematic. Obviously in most cases it’s id
set as primary key, but sometimes when working with legacy databases the name of primary key might be different and in fact we would like to Laravel to do this job for us.
There’s no quick solution for this in current version of Laravel (obviously you can use some workaround) but in upcoming Laravel 5.4 (that should be released next week) there was whereKey
method added, so you can use it instead of specifying name of key directly. So in Laravel 5.4 you could use:
1 |
$email = User::whereKey($id)->value('email'); |
that makes you don’t have to specify id in such case manually and makes using value
method even more useful.
Hi.
In such case I just use
$user = User::findOrFail($id);
$email = $user->email;
or when we try to get user id by email we should validate request before
’email’ => ’email’, Rule::exists(‘users’, email)
both methods will save us from unexistent users and we get right response as 404 not found
In fact if you are fine to use findOrFail you can do it like this:
$email = User::findOrFail($id)->email;
But not always you want to fail if model doesn’t exist. Sometimes you want to go further in such case.
Hi,
laravel optional helper is also useful for this case
$email = optional(User::find($id))->email;
it will return null if it couldn’t found user
Yes, that’s true but it was added later to Laravel and not in 2017 🙂