Signin with facebook - laravel

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);
}
}

Related

Not receiving the response of 400 using axios

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);
}

where and whereIn suddenly stops working in laravel api

In my laravel api am using eloquent query with where condition like this. it was woriking fine before not it is not returning data . when i remove where and whereIn from query then it works fine.In tinker it is fetching data with where and whereIn .
Here is the query
WorkingOrders::whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)->orderBy('id','desc')->get();
whole controller is here
<?php
namespace App\Http\Controllers\GeneralApi;
use App\Events\ConfirmOrder;
use App\Http\Controllers\Controller;
use App\Models\Admin\Gang;
use App\Models\Admin\RightHandMan;
use App\Models\Admin\Staff;
use App\Models\Admin\StaffPivot;
use App\Models\Admin\Worker;
use App\Models\Admin\WorkerArrival;
use App\Models\Admin\WorkSheet;
use App\Models\WorkingOrders;
use App\Notifications\CustomNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class WorkOrderController extends Controller
{
public function workOrdersCompletedCancelled($user_id)
{
$role_id = Auth::guard('staff_api')->user()->roles()->first()->id;
$work_orders = WorkingOrders::when($role_id == 2, function ($q) use ($user_id) {
return $q->where('ranch', $user_id);
})->when($role_id == 4, function ($q) use ($user_id) {
return $q->where('right_hand_man_id', $user_id);
})->when($role_id == 8, function ($q) use ($user_id) {
return $q->where('supervisor', $user_id);
})->when($role_id == 3, function ($q) use ($user_id) {
$gang_ids = DB::table('worker_gang')->where('worker_id', $user_id)->pluck('gang_id')->toArray();
$boss_ids = Gang::where('id', $gang_ids)->pluck('boss_id')->toArray();
return $q->whereIn('gang_boss', $boss_ids);
})->when($role_id == 10, function ($q) use ($user_id) {
return $q->where('truck', $user_id);
})->when($role_id == 1, function ($q) use ($user_id) {
return $q->where('agent', $user_id);
})->when($role_id == 9, function ($q) use ($user_id) {
return $q->where('gang_boss', $user_id);
})->whereIn('status', [0, 9])->with('gang_boss_details.bosses')
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('cutting_company_details:id,name')->with('supervisor_details:id,name')->with('agent_details:id,name')
->with('packaging_company_details:id,name')->with('truck_details:id,name')->with('ranch_details.ranch_owners')->with('right_hand_man:id,name')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->orderBy('id', 'desc')->limit(20)->get();
return response()->json($work_orders);
}
public function workOrders($boss_id)
{
$work_orders = WorkingOrders::where('gang_boss', $boss_id)
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('gang_boss_details.bosses')->with('cutting_company_details:id,name')->with('supervisor_details:id,name')->with('agent_details:id,name')
->with('packaging_company_details')->with('truck_details:id,name')->with('ranch_details.ranch_owners')->with('right_hand_man:id,name')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->orderBy('id', 'desc')->limit(20)->get();
return response()->json($work_orders);
}
public function workOrderDetail($work_order_id)
{
$work_order = WorkingOrders::with('cutting_company_details:id,name')
->with('type_of_cut_details')
->with('type_of_damage_details')
->with('number_of_boxes_details')
->with('size_of_boxes_details')
->with('packaging_company_details.packaging_companies')
->with('supervisor_details')->with('gang_boss_details.bosses')->with('agent_details')->with('ranch_details.ranch_owners')
->with('packaging_company_details')->with('weighing_machine_details:id,name,address,longitude,latitude')->with('worksheet')->with('truck_details.trucks')->with('right_hand_man')->find($work_order_id);
return response()->json($work_order);
}
public function markOrderComplete($id)
{
$work_order = WorkingOrders::find($id);
DB::table('notifications')->where('data','like','%'.$id.'%')->delete();
$work_order->update(['status'=>9,'truck_delivered_fruit_at'=>date('Y-m-d H:i:s')]);
}
public function getRightHandManList()
{
$staff_child = StaffPivot::where('staff_id', auth()->user()->id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 4)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->pluck('id');
$right_hand_men = RightHandMan::whereIn('staff_id', $staffs)->with('staffs')->get();
return response()->json($right_hand_men);
}
public function saveRightHandManList($right_hand_man, $work_order_id)
{
$work_order = WorkingOrders::find($work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 3;
}
$work_order->update(['right_hand_man_id' => $right_hand_man, 'status' => $status,'confirmed_by_boss_at'=>date('Y-m-d H:i:s')]);
$working_order = WorkingOrders::find($work_order_id);
$appDetails = [
'actionText' => Auth::user()->name . ' Se te asignó la orden de corte #' . $work_order_id,
'actionURL' => "/work-order-detail/2/{$working_order->longitude}/{$working_order->latitude}",
];
$rhm = Staff::find($right_hand_man);
$rhm->notify(new CustomNotification($appDetails));
event(new ConfirmOrder($working_order));
return response()->json(['success' => 'Bañero asignado correctamente']);
}
public function getWorkSheet($work_order_id,$time)
{
$work_sheet = WorkSheet::where('work_order_id', $work_order_id)->first();
$work_order = WorkingOrders::find($work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 6;
}
$work_order->update(['status'=>$status,'arrival_to_ranch_at'=>date('Y-m-d H:i:s',strtotime($time))]);
return response()->json($work_sheet);
}
public function saveWorkSheet($work_order_id, $column_name, $column_value)
{
if ($column_value == 'null') {
$column_value = null;
}
$work_sheet = WorkSheet::where('work_order_id', $work_order_id)->update([$column_name => $column_value]);
return response()->json(['status' => true, 'message' => 'Hoja de campo guardada correctamente']);
}
public function addWorker(Request $request)
{
$this->validate($request, [
'name' => 'required',
'password' => 'required',
'location' => 'required',
'longitude' => 'required',
'latitude' => 'required',
'govt_id' => 'required',
'phone_number' => 'required',
'social_security_number' => 'required|unique:staffs,social_security_number',
'time_as_worker' => 'required',
'email' => 'required|email|unique:staffs,email'
]);
$staff = Staff::create([
'name' => $request->name, 'password' => bcrypt($request->password), 'email' => $request->email, 'govt_id' => $request->govt_id,
'social_security_number' => $request->social_security_number, 'phone_number' => $request->phone_number
]);
DB::insert('insert into staff_role (role_id, staff_id) values (?, ?)', [3, $staff->id]);
Worker::create(['staff_id' => $staff->id, 'time_as_worker' => $request->time_as_worker, 'address' => $request->location, 'latitude' => $request->latitude, 'longitude' => $request->longitude]);
StaffPivot::create(['staff_id' => $request->boss_id, 'child_id' => $staff->id]);
return response()->json(['status' => true, 'message' => 'Cortador creado correctamente']);
}
public function addRightHandMan(Request $request)
{
$this->validate($request, [
'name' => 'required',
'password' => 'required',
'location' => 'required',
'longitude' => 'required',
'latitude' => 'required',
'govt_id' => 'required',
'phone_number' => 'required',
'social_security_number' => 'required|unique:staffs,social_security_number',
'time_as_right_hand_man' => 'required',
'email' => 'required|email|unique:staffs,email'
]);
$staff = Staff::create([
'name' => $request->name, 'password' => bcrypt($request->password), 'email' => $request->email, 'govt_id' => $request->govt_id,
'social_security_number' => $request->social_security_number, 'phone_number' => $request->phone_number
]);
DB::insert('insert into staff_role (role_id, staff_id) values (?, ?)', [4, $staff->id]);
RightHandMan::create(['staff_id' => $staff->id, 'time_as_right_hand_man' => $request->time_as_right_hand_man, 'address' => $request->location, 'latitude' => $request->latitude, 'longitude' => $request->longitude]);
StaffPivot::create(['staff_id' => $request->boss_id, 'child_id' => $staff->id]);
return response()->json(['status' => true, 'message' => 'Bañero creado correctamente']);
}
public function getGangWorkers($gang_boss_id, $work_order_id)
{
$gang = Gang::where('boss_id', $gang_boss_id)->first();
$arrived_workers = WorkerArrival::select('worker_id')->where('work_order_id', $work_order_id)->pluck('worker_id');
return response()->json(['workers' => $gang->workers()->get(), 'arrived_workers' => $arrived_workers]);
}
public function getGangWorkersOnly($gang_boss_id)
{
$gang = Gang::where('boss_id', $gang_boss_id)->first();
return response()->json(['workers' => $gang->workers()->get()]);
}
public function storeWorkerArrival(Request $request)
{
WorkerArrival::where('work_order_id', $request->work_order_id)->delete();
foreach ($request->worker_ids as $id) {
if(!WorkerArrival::where('worker_id',$id)->where('work_order_id',$request->work_order_id)->exists()){
WorkerArrival::create(['worker_id' => $id, 'work_order_id' => $request->work_order_id, 'is_reached' => 1]);
}
}
$work_order = WorkingOrders::find($request->work_order_id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 5;
}
$work_order->update(['status'=>$status,'arrival_to_mp_at'=>date('Y-m-d H:i:s',strtotime($request->time))]);
event(new ConfirmOrder(WorkingOrders::find($request->work_order_id)));
return response()->json(['status' => true, 'message' => 'Los cortadores que llegaron han sido registrados']);
}
public function getBossRightHandMan($boss_id)
{
$staff_child = StaffPivot::where('staff_id', $boss_id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 4)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->get();
return response()->json($staffs);
}
public function getBossWorkers($boss_id)
{
// $gang = Gang::where('boss_id', $boss_id)->first();
// return response()->json(['workers' => $gang->workers()->get()]);
$staff_child = StaffPivot::where('staff_id', $boss_id)->pluck('child_id')->toArray();
$staff_role = DB::table('staff_role')->whereIn('staff_id', $staff_child)->where('role_id', 3)->pluck('staff_id')->toArray();
$staffs = Staff::whereIn('id', $staff_role)->get();
$gang = Gang::where('boss_id', $boss_id)->first();
return response()->json(['staff'=>$staffs,'workers'=>$gang->workers()->pluck('worker_id')->toArray()]);
}
public function deleteWorker(Request $request)
{
// Staff::find($request->worker_id)->delete();
// Worker::where('staff_id', $request->worker_id)->delete();
// $gang = Gang::where('boss_id', auth()->user()->id)->first();
// DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
$gang = Gang::where('boss_id', auth()->user()->id)->first();
StaffPivot::where('staff_id', auth()->user()->id)->where('child_id' , $request->worker_id)->delete();
DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
return response()->json(['success', 'Cortador elimando de tu lista de trabajadores']);
}
public function checkExistingStaff(Request $request)
{
if (Staff::where('social_security_number', $request->social_security_number)->exists()) {
return response()->json(['exists' => true, 'data' => Staff::where('social_security_number', $request->social_security_number)->first()]);
}
return response()->json(['exists' => false]);
}
public function addToMyProfile(Request $request)
{
if (!StaffPivot::where('staff_id', auth()->user()->id)->where('child_id', $request->child_id)->exists()) {
StaffPivot::create(['staff_id' => auth()->user()->id, 'child_id' => $request->child_id]);
return response()->json(['message' => 'Agregado correctamente a tu lista de trabajadores']);
}
return response()->json(['message' => 'Ya existe este usuario en tu lista de trabajadores']);
}
public function satffDetail($staff_id)
{
$satff = Staff::find($staff_id);
return response()->json($satff);
}
public function addToGang(Request $request)
{
$gang = Gang::where('boss_id', auth()->user()->id)->first();
if (!DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->exists()) {
DB::table('worker_gang')->insert(['worker_id' => $request->worker_id, 'gang_id' => $gang->id]);
}
return response()->json(['status' => true, 'message' => 'Cortador asignado a la cuadrilla']);
}
public function removeWorkerFromGang(Request $request)
{
$gang = Gang::where('boss_id', auth()->user()->id)->first();
if (DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->exists()) {
DB::table('worker_gang')->where('worker_id', $request->worker_id)->where('gang_id', $gang->id)->delete();
return response()->json(['status' => true, 'message' => 'Eliminado de la cuadrilla']);
}
return response()->json(['status' => true, 'message' => 'Este cortador no está en la cuadrilla']);
}
public function removeRHMFromWorkOrder(Request $request)
{
StaffPivot::where('child_id', $request->rhm)->where('staff_id', auth()->user()->id)->delete();
return response()->json(['success', 'Bañero elimanado de tu lista de trabajadores']);
}
public function OrderComplete($id,$time)
{
$work_order = WorkingOrders::find($id);
if($work_order->status == 8){
$status = 8;
}else{
$status = 7;
}
$work_order->update(['status' => $status,'boss_marked_completed_at'=>date('Y-m-d H:i:s',strtotime($time))]);
return response()->json(['status' => true, 'message' => 'Orden de corte completada']);
}
public function acceptance(Request $request)
{
if ($request->role == 'ranch') {
WorkingOrders::where('id', $request->work_order_id)->update(['ranch_signature' => $request->acceptance]);
}
if ($request->role == 'supervisor') {
WorkingOrders::where('id', $request->work_order_id)->update(['supervisor_signature' => $request->acceptance]);
}
return response()->json(['success' => 'Acción completada']);
}
public function storeWorkerData(Request $request)
{
WorkingOrders::find($request->work_order_id)->update(['boss_marked_completed_at'=>date('Y-m-d H:i:s'),'arrival_to_ranch_at'=>date('Y-m-d H:i:s')]);
WorkSheet::where('work_order_id', $request->work_order_id)->update(['worker_data' => json_encode($request->worker_data),'number_of_box'=>json_encode($request->number_of_boxes)]);
return response()->json(['success' => 'Datos del cortador guardados']);
}
public function getBossPayments(Request $request)
{
if($request->keyword !='false'){
$staff_ids = Staff::select('id')->where('name','like',"%{$request->keyword}%")->pluck('id');
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount')->with(['cutting_company_details:id,name','ranch_details:id,name','worksheet:work_order_id,worker_data,number_of_box'])->whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)
->where(function($query)use($request,$staff_ids){
$query->orWhere('id',$request->keyword)->orWhereIn('ranch',$staff_ids)->orWhereIn('cutting_company',$staff_ids);
})->orderBy('id','desc')->get();
foreach($work_orders as $work_order)
{
$work_order->setAttribute('payment',$this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
}
return response()->json(['work_orders'=>$work_orders]);
}else{
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount')->with(['cutting_company_details:id,name','ranch_details:id,name','worksheet:work_order_id,worker_data,number_of_box'])->whereIn('status',[8,9])->where('gang_boss',auth()->user()->id)->orderBy('id','desc')->get();
dd($work_orders);
foreach($work_orders as $work_order)
{
$work_order->setAttribute('payment',$this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
}
return response()->json(['work_orders'=>$work_orders]);
}
}
public function getWorkOrderWorkerPayment($work_order_id)
{
$work_order = WorkingOrders::with(['worksheet:work_order_id,worker_data,number_of_box','cutting_company_details:id,name','ranch_details:id,name'])->select('id','boss_amount','boss_marked_completed_at','cutting_company','ranch','date_of_work')->where('id',$work_order_id)->first();
$work_order->setAttribute('total_amount_to_pay', $this->getTotalAmountToPayToWorkers($work_order)['total_payment']);
return response()->json(['worker_payment_data'=>$this->getTotalAmountToPayToWorkers($work_order)['worker_payment_data'],'work_order'=>$work_order]);
}
public function getTotalAmountToPayToWorkers($work_order)
{
$total_amount_to_pay = 0;
$worker_payment_data = [];
$work_sheet= $work_order->worksheet;
$data = json_decode($work_sheet->worker_data,true );
$number_of_boxes = json_decode($work_sheet->number_of_box,true);
foreach ((array)$data as $key => $worker_data){
$box = 0;
if(key_exists($key,$number_of_boxes))
{
$box =(int)$number_of_boxes[$key];
}
array_push($worker_payment_data,array('worker_id'=>explode("-",$key)[0],'photo_url'=>Staff::find(explode("-",$key)[0])->photo_url ?? '','worker_name'=>explode("-",$key)[1],'number_of_boxes'=>$box,'comment'=>$worker_data,
'amount_to_pay'=>$box * (float)$work_order->boss_amount ));
$total_amount_to_pay += ($box * (float)$work_order->boss_amount);
}
$worker_payment_data = collect($worker_payment_data);
return array('total_payment'=>$total_amount_to_pay,'worker_payment_data'=>$worker_payment_data);
}
public function submitBossAmount($work_order_id,Request $request)
{
WorkingOrders::find($work_order_id)->update(['boss_amount'=>$request->boss_amount]);
return response()->json(['status'=>true,'message'=>'Boss amount submitted successfully']);
}
public function getWorkerPayments(Request $request,$worker_id)
{
$staff_ids = Staff::select('id')->where('name','like',"%{$request->keyword}%")->pluck('id');
$work_order_ids = WorkSheet::select('work_order_id')->where('worker_data','like',"%{$worker_id}%")->pluck('work_order_id');
$work_orders = WorkingOrders::select('id','cutting_company','ranch','cutting_company_amount','final_kg','boss_amount','date_of_work','boss_marked_completed_at')
->with(['cutting_company_details:id,name','ranch_details:id,name'])
->whereIn('status',[8,9])->whereIn('id',$work_order_ids)
->where(function($query)use($staff_ids,$request){
$query->where('id',$request->keyword)->orWhereIn('ranch',$staff_ids)->orWhereIn('cutting_company',$staff_ids);
})->orderBy('id','desc')->get();
foreach($work_orders as $work_order)
{
$payment = $this->getTotalAmountToPayToWorkersForWorkPortal($work_order,$worker_id);
$work_order->setAttribute('payment',$payment['total_payment']);
$work_order->setAttribute('worker_payment_data',$payment['worker_payment_data']);
$work_order->setAttribute('total_amount_to_pay',$payment['total_payment']);
}
return response()->json(['work_orders'=>$work_orders,'worker_payment_data']);
}
public function getTotalAmountToPayToWorkersForWorkPortal($work_order,$worker_id)
{
$total_amount_to_pay = 0;
$worker_payment_data = [];
$work_sheet= $work_order->worksheet;
$worker_data = json_decode($work_sheet->worker_data,true );
$number_of_boxes = json_decode($work_sheet->number_of_box,true);
foreach ($worker_data as $key => $worker_data){
$box = 0;
if(key_exists($key,$number_of_boxes))
{
$box =(int)$number_of_boxes[$key];
}
if(explode("-",$key)[0] == $worker_id){
$worker_payment_data = array('worker_id'=>explode("-",$key)[0],'photo_url'=>Staff::find(explode("-",$key)[0])->photo_url ?? '','worker_name'=>explode("-",$key)[1],'number_of_boxes'=> $box ,'comment'=>$worker_data,
'amount_to_pay'=> $box * (float)$work_order->boss_amount );
$total_amount_to_pay += ( $box * (float)$work_order->boss_amount);
}
}
$worker_payment_data = collect($worker_payment_data);
return array('total_payment'=>$total_amount_to_pay,'worker_payment_data'=>$worker_payment_data);
}
}
This is the full controller . I also tried to type cast variable which are using in where condition but nothing works.

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.
}
}

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