Method login

mail@pastecode.io avatar
unknown
php
4 years ago
1.5 kB
2
Indexable
Never
public function login(Request $request)
    {
        //validasi data
        $this->validate($request, [
            'email' => 'email',
            'username' => 'string',
            'password' => 'required'
        ]);
        //login dapat menggunakan email atau username
        $user = User::where('email', '=', $request->email)
            ->orWhere('username', '=', $request->username)->first();
//        $username = User::where('username', $request->username)->first();
//        dd($username);
        $status = "error";
        $message = "";
        $data = null;
        $code = 401;
//        echo (gettype($email));
//        echo(gettype($username));
//        echo($email);
        if($user){
            if (Hash::check($request->password, $user->password)){
                $user->generateToken();
                $status = 'success';
                $message = 'Login Success';
                $user->last_login = Carbon::now()->toDateTimeLocalString();
                //tampilkan data user menggunakan method to Array
                $data = $user->toArray();
                $code = 200;
            }
            else{
                $message = "Login gagal, password salah";
            }
        }
        else {
            $message = "Login gagal, username atau email salah";
        }

        return response()->json([
            'status' => $status,
            'message' => $message,
            'data' => $data,
        ], $code);
    }