Not receiving the response of 400 using axios - laravel

This code is from my controller,
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password
];
if (Auth::attempt($credentials)) {
$user = Auth::user();
$success['token'] = $request->user()->createToken('myApp')->plainTextToken;
$success['name'] = $user->name;
$response = [
'success' => true,
'data' => $success,
'message' => 'User login successful',
];
return response()->json($response, 200);
} else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response()->json($response, 400);
}
}
This is my axios method,
const login = async () => {
await axios.post("/api/login", form).then((response) => {
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
});
};
Here in the controller if the condition is false I don't receive any response.If I remove the 400 from return response()->json($response, 400); It gives me a response with 200 code. I don't want it to happen since this is an error. Appreciate it if somebody can point me to the error. Thanks

you need a .catch() here like this:
const login = async () => {
await axios.post("/api/login", form)
.then((response) => {
// Handle API success logic here
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
})
.catch(({message}) => {
// Error response will always take you here
console.log(message)
})
};
UPDATE
from your controller send the response as 200 for both cases:
if($auth){
$response = [
'success' => true,
'message' => 'User login success',
];
return response()->json($response, 200);
} else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response()->json($response, 200);
}
and then make a call as:
const login = async () => {
await axios.post("/api/login", form)
.then((response) => {
// Handle API success logic here
if (response.data.success) {
console.log(response.data.message);
} else {
console.log(response.data.message);
}
})
}
UPDATE #2
in your else part of controller:
else {
$response = [
'success' => false,
'message' => 'User login failed',
];
return response($response["message"], 400);
}

Related

Flutter + Laravel : can't register new user on server

I have flutter app with this register request :
var url = 'xxxxxxx/api/v1/';
// register-----------------
registerToApp(password, username, email, context) async {
var newurl = Uri.parse(url + 'register');
var data = {
'password': password,
'username': username,
'email': email,
};
if (username == '' || password == '' || email == '') {
showSnackBar(context, 'Username and Password and Email must be fill');
} else {
try {
var response = await http.post(newurl, body: data);
var result = jsonDecode(response.body);
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
prefs.setString('username', result['username']);
prefs.setString('token', result['token']);
showSnackBar(context, result['status']);
return result;
} catch (e) {
print(e);
}
}
}
when I tested it on local server it success but after I upload the same api to server I get this error on VsCode :
<script>document.cookie = "humans_21909=1"; document.location.reload(true)
I tested the api on postman on localhost it is succes too on server I get error 409 conflict.
the api created by Lumen :
public function register(Request $request)
{
$id=CreateRandomId::get_id('users');
$password = password_hash($request->password, PASSWORD_DEFAULT);
$users_count= User::where('username',$request->username)->get();
$email_count= User::where('email',$request->email)->get();
$credentials = request(['username', 'password']);
if(count($users_count)>0){
$data = [
'status' => 'username found',
];
}
else {
if (count($email_count)>0){
$data = [
'status' => 'email is found',
];
}
else {
$user = User::create(
[
'id'=>$id,
'username'=>$request->username,
'password'=>$password,
'email'=>$request->email,
'role'=>'user'
]);
if($user){
$credentials = request(['username', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
else{
$data = [
'username'=>$request->username,
'password'=>$password,
'email'=>$request->email,
'status' => 'success',
'token' => $token
];}
}
else{
$data = [
'status' => 'failed',
];
}
}
}
return $data;
}
I copied same controller and router to server ,but don't work, what can I do ?
the route is :
$router->group(['prefix'=>'/api/v1'],function () use ($router) {
$router->get('/',function (){
return "welcome";
});
$router->group(['prefix'=>'/'],function () use ($router) {
$router->post('/register','AuthController#register');
$router->post('/login','AuthController#login');

Maatwebsite\Excel\Validators\ValidationException: The given data was invalid in Laravel

In my Laravel-5.8 project, I am using Maatwebsites-3.1 to import excel
Imports
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class LeavesImport implements WithMultipleSheets
{
public function sheets(): array
{
return [
new FirstLeaveSheetImport()
];
}
}
Which calles this:
class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
protected $staffid, $leavetype, $commencementdate, $resumptiondate, $reliefofficer;
private $errors = []; // array to accumulate errors
use Importable;
// public function onRow(Row $row)
public function model(array $row)
{
$this->staffid = $row['staff_id'];
$this->leavetype = $row['leave_type'];
$this->reliefofficer = $row['relief_officer'];
$this->commencementdate = $row['commencement_date'];
return new HrLeaveRequest([
'employee_id' => $this->getStaffId(),
'leave_type_id' => $this->getLeaveType(),
'commencement_date' => $this->transformDate($row['commencement_date']),
'resumption_date' => $this->transformDate($row['resumption_date']),
'no_of_days' => $row['leave_days'],
'is_adjusted' => 1,
'relief_officer_id' => $this->getReliefOfficer(),
'reason' => $row['reason'] ?? '',
'alternative_email_address' => $row['alternative_email'] ?? '',
'contact_phone_number' => $row['contact_phone'] ?? '',
'contact_address' => $row['contact_address'] ?? '',
'company_id' => Auth::user()->company_id,
'leave_status' => 4,
'is_resumption_activated' => 1,
'resumption_activation_date' => $this->transformDate($row['resumption_date']),
'employee_code' => $row['staff_id'],
'created_by' => Auth::user()->id,
'created_at' => date("Y-m-d H:i:s"),
'is_active' => 1,
]);
}
public function getStaffId(){
if(!empty($this->staffid)){
return HrEmployee::where('employee_code',$this->staffid)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
public function getLeaveType(){
if(!empty($this->leavetype) || !$this->leavetype){
return HrLeaveType::where('leave_type_name',$this->leavetype)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
public function getReliefOfficer(){
return HrEmployee::where('employee_code',$this->reliefofficer)->where('company_id',Auth::user()->company_id)->pluck('employee_code')->first();
}
public function getErrors()
{
return $this->errors;
}
public function rules(): array
{
return [
'staff_id' => 'required|max:15',
'leave_type' => 'required|max:255',
'commencement_date' => 'required',
'leave_days' => 'required|numeric',
'resumption_date' => 'required',
'relief_officer' => 'nullable|max:255',
'reason' => 'nullable|max:255',
'alternative_email' => 'nullable|email|max:255',
'contact_phone' => 'nullable|phone:NG,mobile',
'contact_address' => 'nullable|max:255',
];
}
public function customValidationAttributes()
{
return [
'staff_id' => 'Staff ID',
'leave_type' => 'Leave Type',
'commencement_date' => 'Commencement Date',
'leave_days' => 'Leave Days',
'resumption_date' => 'Resumption Date',
'relief_officer' => 'Duty Relief Officer',
'reason' => 'Reason',
'alternative_email' => 'Alternative Email Address',
'contact_phone' => 'Contact Phone No.',
'contact_address' => 'Contact Address',
];
}
public function validationMessages()
{
return [
'staffid.*required' => "Staff ID is required",
];
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function batchSize(): int
{
return 200;
}
public function headingRow(): int
{
return 1;
}
}
Controller
public function import(Request $request){
$request->validate([
'file' => 'required|max:10000|mimes:xlsx,xls',
]);
$path1 = $request->file('file')->store('temp');
$path=storage_path('app').'/'.$path1;
try{
Excel::import(new LeavesImport, $path);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
Log::error($e);
$errormessage = "";
// dd($failures);
foreach ($failures as $failure) {
$errormess = "";
foreach($failure->errors() as $error)
{
$errormess = $errormess.$error;
}
$errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
}
// Session::flash('error', 'Excel file is not imported!');
Session::flash('error', $errormessage);
// return redirect()->route('leave.leave_adjustments.index');
return back();
}catch (\Illuminate\Database\QueryException $e)
{
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Log::error($e);
DB::rollback();
Session::flash('error', 'You have a duplicate entry problem!');
}
return back();
}
Session::flash('success', 'Leave Records Imported Successfully');
return redirect()->route('leave.leave_reviews.index_hr');
}
When I tried t upload the excel file it shows that it was successful. But I found that no data is store in the database. So when I checked error Log, I saw these:
[2020-11-16 07:38:53] production.ERROR: Maatwebsite\Excel\Validators\ValidationException: The given data was invalid. in C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Validators\RowValidator.php:62
Stack trace:
#0 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Imports\ModelManager.php(166): Maatwebsite\Excel\Validators\RowValidator->validate(Array, Object(App\Imports\FirstLeaveSheetImport))
#1 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Imports\ModelManager.php(53): Maatwebsite\Excel\Imports\ModelManager->validateRows(Object(App\Imports\FirstLeaveSheetImport))
#2 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Imports\ModelImporter.php(70): Maatwebsite\Excel\Imports\ModelManager->flush(Object(App\Imports\FirstLeaveSheetImport), true)
#3 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Sheet.php(248): Maatwebsite\Excel\Imports\ModelImporter->import(Object(PhpOffice\PhpSpreadsheet\Worksheet\Worksheet), Object(App\Imports\FirstLeaveSheetImport), 2)
#4 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Reader.php(111): Maatwebsite\Excel\Sheet->import(Object(App\Imports\FirstLeaveSheetImport), 2)
#5 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Concerns\ManagesTransactions.php(29): Maatwebsite\Excel\Reader->Maatwebsite\Excel\{closure}(Object(Illuminate\Database\MySqlConnection))
#6 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Transactions\DbTransactionHandler.php(30): Illuminate\Database\Connection->transaction(Object(Closure))
#7 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Reader.php(115): Maatwebsite\Excel\Transactions\DbTransactionHandler->__invoke(Object(Closure))
#8 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Excel.php(146): Maatwebsite\Excel\Reader->read(Object(App\Imports\LeavesImport), 'C:\\xampp\\htdocs...', 'Xlsx', NULL)
#9 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php(239): Maatwebsite\Excel\Excel->import(Object(App\Imports\LeavesImport), 'C:\\xampp\\htdocs...')
#10 C:\xampp\htdocs\myapp\app\Http\Controllers\Leave\LeaveAdjustmentsController.php(360): Illuminate\Support\Facades\Facade::__callStatic('import', Array)
#11 [internal function]: App\Http\Controllers\Leave\LeaveAdjustmentsController->import(Object(Illuminate\Http\Request))
How do I detect and rectify the error?
Thanks
From the docs
try {
$import->import('import-users.xlsx');
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
}

Signin with facebook

In my code I check the account status from users table if it is 1 then shows the detail of user. By default the value of account status is 1. When i run the code that condition doesn't work. Here is my code. Please Help. Thanks in advance.
public function signInFacebook(SignInFacebookUser $request)
{
if($profile_picture = $request->hasFile('profile_picture')) {
$profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
$request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
$profile_picture = 'Storage/ProfileImages/'.$profile_picture;
} else {
$profile_picture = NULL;
}
try {
$user = User::updateOrCreate([
'facebook_id' => $request->input('facebook_id'),
],
[
'name' => $request->input('name'),
'surname' => $request->input('surname'),
'date_of_birth' => $request->input('date_of_birth'),
'email' => $request->input('email'),
'city' => $request->input('city'),
'university' => $request->input('university'),
'profile_picture' => $profile_picture,
]);
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
return response()->json(['message' => 'Duplicate Entry']);
}
}
$token = JWTAuth::fromUser($user);
if($user->account_status == 1) {
$userDetail = $user->where('id', $user->id)->first();
return response()->json(['token' => $token, 'user' => $userDetail], 200);
}
else {
return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
}
}
Here is the changing I done in my code and it works.
public function signInFacebook(SignInFacebookUser $request)
{
if($profile_picture = $request->hasFile('profile_picture')) {
$profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
$request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
$profile_picture = 'Storage/ProfileImages/'.$profile_picture;
} else {
$profile_picture = NULL;
}
try {
$user = User::updateOrCreate([
'facebook_id' => $request->input('facebook_id'),
],
[
'name' => $request->input('name'),
'surname' => $request->input('surname'),
'date_of_birth' => $request->input('date_of_birth'),
'email' => $request->input('email'),
'city' => $request->input('city'),
'university' => $request->input('university'),
'profile_picture' => $profile_picture,
]);
} catch (QueryException $e) {
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
return response()->json(['message' => 'Duplicate Entry']);
}
}
if(!$user) {
return response()->json(['message' => 'failed to signin with facebook'], 200);
}
$userDetail = $user->where('id', $user->id)->first();
if ($userDetail->account_status == 1) {
$token = JWTAuth::fromUser($user);
return response()->json(['token' => $token, 'user' => $userDetail], 200);
} else {
return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
}
}

login error message when user is inactive

I have Laravel code that of login auth page, the problem is that when I login the inactive user, I should get error message that your user is not activated.
My code
public function postLogin(Request $request)
{
$credentials = $request->only(['username', 'password']);
$validator = Validator::make($credentials, [
'username' => 'required', 'password' => 'required',
]);
// If the user is activated then value will be 1 and not activated user will 0
// <--- THIS LINE
if(!$credentials['active'] = 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
if (Auth::guard('admin')->attempt($credentials)) {
admin_toastr(trans('admin::lang.login_successful'));
return redirect()->intended(config('admin.prefix'));
}
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
You haven't used the correct operator in your if statement. change
if(!$credentials['active'] = 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
to
if(!$credentials['active'] == 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
OR
if($credentials['active'] != 1)
{
return Redirect::back()->withInput()->withErrors($validator);
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}

ErrorException in Encrypter.php line 106: unserialize(): Error at offset 0 of 82 bytes

any some body can help me to fix that error.
this my error :
enter image description here
here his my code
public function dologin() {
$input = Input::all();
$rules = [
'username' => 'required',
'password' => 'required|min:6',
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
Alert()->info('Username dan password tidak boleh kosong Panjang Password minimal 6 huruf', 'Info')->persistent('OK');
return redirect()->route('auth.login');
} else {
$user = CoreUser::where('username', $input['username'])->orWhere('user_email', $input['username'])->first();
if ($user) {
if($user->user_active != 1){
Alert()->error('Username sudah tidak aktif', 'Info')->persistent('OK');
return redirect()->route('auth.login')->withErrors("User tidak aktif");
}
if (Hash::check($input['password'], $user->password)) {
$session = [
'username' => $user->username,
'password' => $input['password']
];
$remember = true;
if (Auth::attempt($session, true)) {
return redirect()->intended('/');
} else {
// no action
dd("failed attempt");
}
} else {
//dd("hash check failed");
// no action
}
}
Alert()->error('Username dan password tidak sesuai', 'Gagal')->persistent('OK');
return redirect()->route('auth.login')->withErrors("Invalid Username or Password");
}
}

Resources