Here is my code which is working fine with MySQL but when I switch MySQL to MongoDB registration is working properly but the login attempt is returning false.
I am creating an API for login and registration for my project.
I have also implemented JWT token package in laravel 9.
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Carbon\Carbon;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','register']]);
}
public function login(Request $request)
{
$request->validate([
'strEmail' => 'required|string|email',
'strPassword' => 'required|string',
]);
$credentials = $request->only('strEmail', 'strPassword');
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json([
'status' => 'error',
'message' => 'Unauthorized',
], 401);
}
$user = Auth::user();
return response()->json([
'status' => 'success',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
public function register(Request $request){
$request->validate([
'strFirstName' => 'required|string|max:255',
'strLastName' => 'required|string|max:255',
'strEmail' => 'required|string|email|max:255|unique:users',
'strPassword' => 'required|string|min:6',
]);
$user = User::create([
'strFirstName' => $request->strFirstName,
'strLastName' => $request->strLastName,
'strEmail' => $request->strEmail,
'strPassword' => Hash::make($request->strPassword),
'isLogin' => 1,
'LastLoginDate'=> Carbon::now(),
'EnterDatetime' => new \DateTime(),
'IP' => \Request::ip(),
]);
$token = Auth::login($user);
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
}
here is the user model
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
please help.
I have tried this code with MySQL and both registration and login work with MySQL.
I finally solved it. Auth only accepts the password field as a "password".