1. mudragel

    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.

  2. Ahmed Waleed

    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

Leave a Reply

Your email address will not be published. Required fields are marked *