laravel select where and where condition

Viewed 237938

I have this basic query i want to perform but an error keeps coming up. Probably due to my newness to laravel.

here is the code:

$userRecord = $this->where('email', $email)->where('password', $password);
        echo "first name: " . $userRecord->email;

I am trying to get the user record matching the credentials where email AND password are a match. This is throwing an error:

Undefined property: Illuminate\Database\Eloquent\Builder::$email

I've checked the email and password being passed to the function, and they are holding values. what is the problem here?

Thanks,

8 Answers

Here is shortest way of doing it.

$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();
$userRecord = $this->where('email', $email)->where('password', $password);

in the above code , you are just requesting for Eloquent object , not requesting for the data,

   $userRecord = $this->where('email', $email)->where('password', $password)->first();

so that, you can get the first data, from the given credentials by default ordering DESC with PK, in case of multiple data with the same credentials. but you have to handle the exception, in case of no matching data. you have one more option to achieve the same.

$userRecord = $this->where('email', $email)->where('password', $password)->firstOrfail();

in the above snippets, in case of no data, it will automatically throw a 404 error.

also, you can have alternative snippets

$filter['email']=$email;
$filter['password']=$password;
$userRecord = $this->where($filter)->first();

That's it

Related