I am building laravel API of my website . I am using laravel 5.3
I am using the API in building mobile app .
In login section, there are two fields :
In my DB , email and username are different columns.
Here is the function:
public function authenticate()
{
$credentials=request()->only('username','password');
try {
$token=JWTAuth::attempt($credentials);
if(!$token){
return response()->json(['error'=>'credentials wrong'],401);
}
}
catch(JWTException $e) {
return response()->json(['error'=>'something_went_wrong'],500);
}
return response()->json(['token'=>$token],200);
}
Here only username is used,I want to use both username and password.
If need any other info please ask.
ty:)
You can use FILTER_VALIDATE_EMAIL function Like this:-
$login_type = filter_var( $data['email'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';
And then pass in auth attempt function like this:-
Auth::attempt([$login_type => $data['email'], 'password' => $data['password']])
In your case:-
According to your Html you have used two input
<input type="text"required autocomplete="off" name="loginEmail" id="inputname"/>
<input type="password"required autocomplete="off" name="loginPassword" id="inputpassword"/>
And your function is:-
public function authenticate(Request $request)
{
$data = $request->all();
$login_type = filter_var( $data['loginEmail'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';
//$credentials=request()->only('username','password');
try {
$token=JWTAuth::attempt([$login_type => $data['loginEmail'], 'password' => $data['loginPassword']]);
if(!$token){
return response()->json(['error'=>'credentials wrong'],401);
}
}
catch(JWTException $e) {
return response()->json(['error'=>'something_went_wrong'],500);
}
return response()->json(['token'=>$token],200);
}
Hope it Helps!
In postman I was using key in the body called 'username' so here instead of loginEmail , username will come and it will work fine ! ty