使用?:laravel中的速记

时间:2017-06-08 08:29:09

标签: php laravel ternary-operator

我有一个登录功能,用于使用电话号码登录用户。我从用户那里获取电话号码,然后使用电话号码获取匹配的电子邮件地址。

为此我有这个代码

public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {

当数字错误时,我收到此错误

Trying to get property of non-object

要解决此问题,我希望变量$getEmail等于none@dont.com,这会像所有其他错误的电子邮件和密码组合一样失败。

如何确保我在用于获取电子邮件的这一行中发现错误

User::where('users_telephone_number', '=',$phone )->first()->email;

4 个答案:

答案 0 :(得分:1)

您是imediatly尝试获取您尝试获取的对象的电子邮件属性。 我建议使用方法 String test = "test"; String fileName = "kyriakos.txt"; saveDataToFile(AnswerQ1, fileName); public void saveDataToFile(String answer, String fileName) { Log.d("Checks", "Trying to save data"); try { // Set up the file directory String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder"; File fileDirectory = new File(filePath); fileDirectory.mkdirs(); Log.d("Checks", "Directory created"); // Set up the file itself File textFile = new File(fileDirectory, fileName); textFile.createNewFile(); Log.d("Checks", "File created"); // Write to the file FileOutputStream fileOutputStream = new FileOutputStream(textFile,true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); outputStreamWriter.append(" " +"\"fcov\":" +" "+ "\""+answer+"\"," + "\n" ); outputStreamWriter.close(); fileOutputStream.close(); Toast.makeText(getApplicationContext(), "Done writing to SD card", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }} ,当找不到结果时,会抛出findOrFail,这将返回NotFoundException

总的来说,它看起来像这样:

404 not found

答案 1 :(得分:0)

先检查$ user,然后访问该电子邮件。

$user = User::where('users_telephone_number', '=',$phone )->first();
$email = isset($user) ? $user->email : 'default string';

答案 2 :(得分:0)

$phone = $request->get('phone');
$getEmail = User::where('users_telephone_number', '=',$phone )->first();
$email = $getEmail ? $getEmail->email : null;
if(!$email)
    return abort(400);

答案 3 :(得分:0)

或测试null:

$user = User::where('users_telephone_number', '=',$phone )->first();
$email = $user ? $user->email : 'default string';

如果您的查询没有返回任何User实例,它将返回默认的空值。

或者......你可以测试电子邮件

$password = $request->get('password');
$user = User::where('users_telephone_number', '=', $phone)->whereNotNull('email')->first();

if ($user && Auth::attempt([$user->email, $password], true)) {
    ...
}