where and whereIn suddenly stops working in laravel api - laravel
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.
Related
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); } }
Laravel Sms Configuration
We using to private message service. I want send sms notification to message received person. I searched but couldn't find. But I could do this much maybe wrong maybe right. Sometimes the page gave a complete data error I Understand may have given the recipient wrong I do this code ; if(config('config.task_sms_notification')){ $message = 'Merhaba, Suit 13\'de Tarafiniza Yeni Mesaj Gonderildi. Gonderen: '.$request->input('to_user_id'); $user = $new_message->to_user_id; if($user->Profile->mobile) $user->notify(new TaskNotification($message,$task)); } } Private message service codes; public function __construct() { $this->middleware('feature_available:enable_message'); } public function validateLiveMessage($type,$value){ $message = Message::where($type,'=',$value)->where(function($query) { $query->where(function($query1){ $query1->where('from_user_id','=',\Auth::user()->id) ->where('delete_sender','=','0'); })->orWhere(function($query2){ $query2->where('to_user_id','=',\Auth::user()->id) ->where('delete_receiver','=','0'); }); })->first(); return ($message) ? : 0; } public function validateDeleteMessage($type,$value){ $message = Message::where($type,'=',$value)->where(function($query) { $query->where(function($query1){ $query1->where('from_user_id','=',\Auth::user()->id) ->where('delete_sender','=','1'); })->orWhere(function($query2){ $query2->where('to_user_id','=',\Auth::user()->id) ->where('delete_receiver','=','1'); }); })->first(); return ($message) ? : 0; } public function index(){ $table_data['inbox-table'] = array( 'source' => 'message/inbox', 'title' => 'Inbox', 'id' => 'inbox_table', 'data' => array( trans('messages.option'), trans('messages.from'), trans('messages.subject'), trans('messages.date_time'), '' ) ); $table_data['sent-table'] = array( 'source' => 'message/sent', 'title' => 'Sent', 'id' => 'sent_table', 'data' => array( trans('messages.option'), trans('messages.to'), trans('messages.subject'), trans('messages.date_time'), '' ) ); $table_data['starred-table'] = array( 'source' => 'message/starred', 'title' => 'Starred', 'id' => 'starred_table', 'data' => array( trans('messages.option'), '', trans('messages.subject'), trans('messages.date_time'), '' ) ); $table_data['trash-table'] = array( 'source' => 'message/trash', 'title' => 'Trash', 'id' => 'trash_table', 'data' => array( trans('messages.option'), '', trans('messages.subject'), trans('messages.date_time'), '' ) ); $users = \App\User::where('id','!=',\Auth::user()->id)->get()->pluck('full_name','id')->all(); $messages = Message::whereToUserId(\Auth::user()->id) ->whereDeleteReceiver('0')->whereNull('reply_id') ->get(); $count_inbox = count($messages); $assets = ['summernote','datatable']; $menu = 'message'; return view('message.index',compact('users','count_inbox','assets','menu','table_data')); } public function starred(Request $request){ $message = $this->validateLiveMessage('token',$request->input('token')); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); if(\Auth::user()->id == $message->from_user_id) $message->is_starred_sender = ($message->is_starred_sender) ? 0 : 1; else $message->is_starred_receiver = ($message->is_starred_receiver) ? 0 : 1; $message->save(); return response()->json(['status' => 'success']); } public function lists($type,Request $request){ if($type == 'inbox') $inbox_message = Message::whereToUserId(\Auth::user()->id) ->select(\DB::raw('reply_id')) ->whereDeleteReceiver(0) ->whereNotNull('reply_id') ->groupBy('reply_id') ->get() ->pluck('reply_id') ->all(); elseif($type == 'sent') $sent_message = Message::whereFromUserId(\Auth::user()->id) ->select(\DB::raw('reply_id')) ->whereDeleteSender(0) ->whereNotNull('reply_id') ->groupBy('reply_id') ->get() ->pluck('reply_id') ->all(); if($type == 'sent') $messages = Message::where(function($query) use($sent_message){ $query->where(function($query1) use($sent_message){ $query1->where('from_user_id','=',\Auth::user()->id) ->where('delete_sender','=','0') ->whereNull('reply_id'); })->orWhereIn('id',$sent_message); })->orderBy('created_at','desc')->get(); elseif($type == 'inbox') $messages = Message::where(function($query) use($inbox_message){ $query->where(function($query1) use($inbox_message){ $query1->where('to_user_id','=',\Auth::user()->id) ->where('delete_receiver','=','0') ->whereNull('reply_id'); })->orWhereIn('id',$inbox_message); })->orderBy('created_at','desc')->get(); elseif($type == 'starred') $messages = Message::where(function($query){ $query->where(function($query1){ $query1->where('from_user_id','=',\Auth::user()->id) ->where('delete_sender','=',0) ->where('is_starred_sender','=',1); })->orWhere(function($query2){ $query2->where('to_user_id','=',\Auth::user()->id) ->where('delete_receiver','=',0) ->where('is_starred_receiver','=',1); }); })->orderBy('created_at','desc')->get(); elseif($type == 'trash') $messages = Message::where(function($query){ $query->where(function($query1){ $query1->where('from_user_id','=',\Auth::user()->id) ->where('delete_sender','=',1); })->orWhere(function($query2){ $query2->where('to_user_id','=',\Auth::user()->id) ->where('delete_receiver','=',1); }); })->orderBy('created_at','desc')->get(); $rows=array(); foreach($messages as $message){ $starred = 0; if(\Auth::user()->id == $message->from_user_id) $starred = ($message->is_starred_sender) ? 1 : 0; else $starred = ($message->is_starred_receiver) ? 1 : 0; $option = (($type != 'trash') ? '<div class="btn-group btn-group-xs"> <i class="fa fa-arrow-circle-right"></i>' : ''). (($type != 'trash') ? ' <i class="fa fa-'.($starred ? 'star starred' : 'star-o').'"></i>' : ''). (($type == 'trash') ? ' <i class="fa fa-retweet" data-toggle="tooltip" data-title="'.trans('messages.restore').'"></i>' : ''). (($type != 'trash') ? delete_form(['message.trash',$message->id]) : delete_form(['message.destroy',$message->id])).'</div>'; $source = (\Auth::user()->id == $message->from_user_id) ? $message->UserTo->full_name : $message->UserFrom->full_name; if($type == 'starred' || $type == 'trash') $source .= (\Auth::user()->id == $message->from_user_id) ? ' <span class="label label-success">Sent</span>' : ' <span class="label label-info">Inbox</span>'; $unread = 0; if($type == 'inbox' && ((!$message->is_read && $message->to_user_id == \Auth::user()->id) || ($message->Replies->where('to_user_id','=',\Auth::user()->id)->where('is_read','=',0)->count()))) $unread = 1; if($message->Replies->count() && ($type == 'inbox' || $type == 'sent')) $source .= ' ('.(($message->Replies->where('to_user_id','=',\Auth::user()->id)->where('delete_receiver','=',0)->count())+($message->Replies->where('from_user_id','=',\Auth::user()->id)->where('delete_sender','=',0)->count())+1).')'; if($type == 'trash' && $message->reply_id != null && (($message->Reply->to_user_id == \Auth::user()->id && $message->Reply->delete_receiver == 1) || ($message->Reply->from_user_id == \Auth::user()->id && $message->Reply->delete_sender == 1))) $show = 0; else $show = 1; if($show) $rows[] = array('<div class="btn-group btn-group-xs">'.$option.'</div>', ($unread) ? ('<strong>'.$source.'</strong>') : $source, ($unread) ? ('<strong>'.$message->subject.'</strong>') : $message->subject, ($unread) ? ('<strong>'.showDateTime($message->created_at).'</strong>') : showDateTime($message->created_at), ($message->attachments) ? '<i class="fa fa-paperclip"></i>' : '' ); } $list['aaData'] = $rows; return json_encode($list); } public function forward($token){ $message = $this->validateLiveMessage('token',$token); if(!$message) return view('global.error',['message' => trans('messages.permission_denied')]); \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->update(['is_temp_delete' => 0]); $uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->get(); $users = \App\User::where('id','!=',\Auth::user()->id)->get()->pluck('full_name','id')->all(); return view('message.forward',compact('message','users','uploads')); } public function postForward(Request $request, $token){ $message = $this->validateLiveMessage('token',$token); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); $validation = Validator::make($request->all(),[ 'to_user_id' => 'required', 'subject' => 'required' ]); $friendly_name = array('to_user_id' => 'receiver'); $validation->setAttributeNames($friendly_name); if($validation->fails()) return response()->json(['message' => $validation->messages()->first(), 'status' => 'error']); $existing_upload = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereIsTempDelete(0)->count(); $new_upload_count = 0; foreach($request->input('upload_key') as $upload_key) $new_upload_count += \App\Upload::whereModule('message')->whereUploadKey($upload_key)->count(); if($existing_upload + $new_upload_count > config('constant.max_file_allowed.message')) return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']); $new_message = new Message; $new_message->subject = $request->input('subject'); $new_message->body = clean($request->input('body'),'custom'); $new_message->attachments = $message->attachments; $new_message->to_user_id = $request->input('to_user_id'); $new_message->from_user_id = \Auth::user()->id; $new_message->token = randomString(30); $new_message->attachments = ($existing_upload + $new_upload_count) ? 1 : 0; $new_message->save(); $existing_uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->whereIsTempDelete(0)->get(); foreach($existing_uploads as $existing_upload){ $new_upload_key = randomString(40); $new_upload = new \App\Upload; $new_upload->user_id = \Auth::user()->id; $new_upload->module = 'message'; $new_upload->user_filename = $existing_upload->user_filename; $upload_attachment = explode('.',$existing_upload->attachments); $new_upload->attachments = str_random(50).'.'.$upload_attachment[1]; $new_upload->module_id = $new_message->id; $new_upload->upload_key = $new_upload_key; $new_upload->status = 1; $new_upload->save(); \Storage::copy('attachments/'.$existing_upload->attachments, 'attachments/'.$new_upload->attachments); } foreach($request->input('upload_key') as $upload_key){ $uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get(); $new_upload_key = randomString(40); foreach($uploads as $upload){ $upload->module_id = $new_message->id; $upload->status = 1; $upload->save(); \Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments); } } \App\Upload::whereModule('message')->whereModuleId($message->id)->whereStatus(1)->whereIsTempDelete(1)->update(['is_temp_delete' => 0]); $this->logActivity(['module' => 'message','module_id' => $new_message->id,'activity' => 'forwarded']); return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']); } public function load(Request $request){ $message = $this->validateLiveMessage('token',$request->input('token')); if($message){ $replies = Message::where('reply_id','=',$message->id)->where(function($query){ $query->where(function($query1){ $query1->where('to_user_id','=',\Auth::user()->id)->where('delete_receiver','=','0'); })->orWhere(function($query2){ $query2->where('from_user_id','=',\Auth::user()->id)->where('delete_sender','=','0'); }); })->get(); return view('message.load',compact('message','replies'))->render(); } } public function reply($id,Request $request){ $message = $this->validateLiveMessage('id',$id); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); $file_uploaded_count = \App\Upload::whereIn('upload_key',$request->input('upload_key'))->count(); if($file_uploaded_count > config('constant.max_file_allowed.message')) return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']); $data = $request->all(); $reply = new Message; $reply->fill($data); $reply->token = randomString(30); $reply->subject = 'Re: '.$message->subject; $reply->body = clean($request->input('body'),'custom'); $reply->from_user_id = \Auth::user()->id; $reply->reply_id = $message->id; $reply->attachments = ($file_uploaded_count) ? 1 : 0; $reply->is_read = 0; $reply->to_user_id = ($message->from_user_id == \Auth::user()->id) ? $message->to_user_id : $message->from_user_id; $reply->save(); foreach($request->input('upload_key') as $upload_key){ $uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get(); foreach($uploads as $upload){ $upload->module_id = $reply->id; $upload->status = 1; $upload->save(); \Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments); } } $this->logActivity(['module' => 'message','module_id' => $reply->id,'activity' => 'replied']); return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']); } public function store(MessageRequest $request){ $file_uploaded_count = \App\Upload::whereIn('upload_key',$request->input('upload_key'))->count(); if($file_uploaded_count > config('constant.max_file_allowed.message')) return response()->json(['message' => trans('messages.max_file_allowed',['attribute' => config('constant.max_file_allowed.message')]),'status' => 'error']); $data = $request->all(); $message = new Message; $message->fill($data); $message->token = randomString(30); $message->body = clean($request->input('body'),'custom'); $message->from_user_id = \Auth::user()->id; $message->is_read = 0; $message->attachments = ($file_uploaded_count) ? 1 : 0; $message->save(); foreach($request->input('upload_key') as $upload_key){ $uploads = \App\Upload::whereModule('message')->whereUploadKey($upload_key)->get(); foreach($uploads as $upload){ $upload->module_id = $message->id; $upload->status = 1; $upload->save(); \Storage::move('temp_attachments/'.$upload->attachments, 'attachments/'.$upload->attachments); } } $this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'sent']); return response()->json(['message' => trans('messages.message').' '.trans('messages.sent'), 'status' => 'success']); } public function download($file){ $upload = \App\Upload::whereAttachments($file)->whereModule('message')->whereStatus(1)->first(); if(!$upload) return redirect('/message')->withErrors(trans('messages.invalid_link')); $message = Message::find($upload->module_id); if(!$message) return redirect('/message')->withErrors(trans('messages.invalid_link')); if($message->to_user_id != \Auth::user()->id && $message->from_user_id != \Auth::user()->id) return redirect('/message')->withErrors(trans('messages.permission_denied')); if(!\Storage::exists('attachments/'.$upload->attachments)) return redirect('/message')->withErrors(trans('messages.file_not_found')); $download_path = storage_path().config('constant.storage_root').'attachments/'.$upload->attachments; return response()->download($download_path, $upload->user_filename); } public function view($token){ $message = $this->validateLiveMessage('token',$token); if(!$message) return redirect('/message')->withErrors(trans('messages.invalid_link')); if($message->Replies->count()) Message::where('reply_id','=',$message->id)->where('to_user_id','=',\Auth::user()->id)->update(['is_read' => 1]); if($message->reply) return redirect('/message/'.$message->Reply->token); if(\Auth::user()->id == $message->to_user_id){ $message->is_read = 1; $message->save(); } $assets = ['summernote']; return view('message.view',compact('message','assets')); } public function trash($id,Request $request){ $message = $this->validateLiveMessage('id',$id); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); $this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'trashed']); if($message->to_user_id == \Auth::user()->id) $message->delete_receiver = 1; else $message->delete_sender = 1; $message->save(); if($message->Replies->count()){ $sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$sender_messages)->update(['delete_sender' => 1]); $receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 1]); } return response()->json(['message' => trans('messages.message').' '.trans('messages.trashed'), 'status' => 'success']); } public function restore(Request $request){ $message = $this->validateDeleteMessage('token',$request->input('token')); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); if($message->reply_id != null && (($message->Reply->to_user_id == \Auth::user()->id && $message->Reply->delete_receiver > 0) || ($message->Reply->from_user_id == \Auth::user()->id && $message->Reply->delete_sender > 0))) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); $this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'restored']); if($message->to_user_id == \Auth::user()->id) $message->delete_receiver = 0; else $message->delete_sender = 0; $message->save(); if($message->Replies->count()){ $sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$sender_messages)->update(['delete_sender' => 0]); $receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 0]); } return response()->json(['message' => trans('messages.message').' '.trans('messages.restored'), 'status' => 'success']); } public function destroy($id,Request $request){ $message = $this->validateDeleteMessage('id',$id); if(!$message) return response()->json(['message' => trans('messages.invalid_link'), 'status' => 'error']); if(getMode()){ $uploads = \App\Upload::whereModule('message')->whereModuleId($message->id)->get(); foreach($uploads as $upload) \Storage::delete('attachments/'.$upload->attachments); \App\Upload::whereModule('message')->whereModuleId($message->id)->delete(); } $this->logActivity(['module' => 'message','module_id' => $message->id,'activity' => 'deleted']); if($message->to_user_id == \Auth::user()->id) $message->delete_receiver = 2; else $message->delete_sender = 2; $message->save(); if($message->Replies->count()){ $sender_messages = $message->Replies->where('from_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$sender_messages)->update(['delete_sender' => 2]); $receiver_messages = $message->Replies->where('to_user_id','=',\Auth::user()->id)->pluck('id'); Message::whereIn('id',$receiver_messages)->update(['delete_receiver' => 2]); } return response()->json(['message' => trans('messages.message').' '.trans('messages.deleted'), 'status' => 'success']); } }
Does this line $user = $new_message->to_user_id; Return the Eloquent Model of the User or just the ID ? Is it a relation ? If not, as in the next lines you seem to try to access a relation. if($user->Profile->mobile) It is a wild guess, but maybe you need to do something like this $user = User::findOrFail($new_message->to_user_id); or setup a relation in Message model to be able to get the User object
Dropdownlist selected value not showing while updating the form
Here i like to explain my problem i have dropdownlist called companytype, it contains value 1+1, 1+2, 1+3, 1+4, 1+5, 1+6, 1+7 while creating form i have a select a value eg:1+4 and store, but the same while updating the value getting change as select companytype [prompt] <?= $form->field($model, 'companytype')->dropDownList([ '1' => '1+1', '2' => '1+2', '3' => '1+3', '4' => '1+4', '5' => '1+5', '6' => '1+6', '7' => '1+7', ], ['prompt' => 'Select Company Type', ]) ?> here i have added two images you can easily understand my question gridview of created form updating the same form updated: mycontroller code: public function actionCreate() { if(Yii::$app->user->can( 'create-company' ) ) { $model = new Company(); if ($model->load(Yii::$app->request->post()) ) { $model->createdat = date('Y-m-d'); $ro = $model->relationoption; if($ro == 'fixed') { $commaList = implode(', ', $model->relation); $model->relation = $commaList; } $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } else { throw new ForbiddenHttpException; } } controller code for update public function actionUpdate($id) { if(Yii::$app->user->can('update-company')) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) ) { $model->updatedat = date('Y-m-d h:m:s'); $ro = $model->relationoption; if($ro == 'fixed') { $commaList = implode(', ', $model->relation); $model->relation = $commaList; } $model->save(); return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } else { throw new ForbiddenHttpException; } } Is there anyone to answer, pls answer me
I dont see $model->companytype = 4 in your update action. Can you add it to your update action and check. So your update action should look like: public function actionUpdate($id) { if(Yii::$app->user->can('update-company')) { $model = $this->findModel($id); $model->companytype = 4; if ($model->load(Yii::$app->request->post()) ) { $model->updatedat = date('Y-m-d h:m:s'); $ro = $model->relationoption; if($ro == 'fixed') { $commaList = implode(', ', $model->relation); $model->relation = $commaList; } $model->save(); return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } else { throw new ForbiddenHttpException; } }
This webpage has a redirect loop in Laravel 4
I'm busy with a tutorial and I ended up getting an error that says This webpage has a redirect loop I know that the problem is here in my routes.php Route::group(["before" => "guest"], function(){ $resources = Resource::where("secure", false)->get(); foreach($resources as $resource){ Route::any($resource->pattern, [ "as" => $resource->name, "uses" => $resource->target ]); } }); Route::group(["before" => "auth"], function(){ $resources = Resource::where("secure", true)->get(); foreach($resources as $resource){ Route::any($resource->pattern, [ "as" => $resource->name, "uses" => $resource->target ]); } }); UserController class UserController extends \BaseController { public function login() { if($this->isPostRequest()) { $validator = $this->getLoginValidator(); if($validator->passes()) { $credentials = $this->getLoginCredentials(); if(Auth::attempt($credentials)){ return Redirect::route("user/profile"); } return Redirect::back()->withErrors([ "password" => ["Credentials invalid."] ]); }else{ return Redirect::back() ->withInput() ->withErrors($validator); } } return View::make("user/login"); } protected function isPostRequest() { return Input::server("REQUEST_METHOD") == "POST"; } protected function getLoginValidator() { return Validator::make(Input::all(), [ "username" => "required", "password" => "required" ]); } protected function getLoginCredentials() { return [ "username" => Input::get("username"), "password" => Input::get("password") ]; } public function profile() { return View::make("user/profile"); } public function request() { if($this->isPostRequest()){ $response = $this->getPasswordRemindResponse(); if($this->isInvalidUser($response)){ return Redirect::back() ->withInput() ->with("error", Lang::get($response)); } return Redirect::back() ->with("status", Lang::get($response)); } return View::make("user/request"); } protected function getPasswordRemindResponse() { return Password::remind(Input::only("email")); } protected function isInvalidUser($response) { return $response === Password::INVALID_USER; } public function reset($token) { if($this->isPostRequest()){ $credentials = Input::only( "email", "password", "password_confirmation" ) + compact("token"); $response = $this->resetPassword($credentials); if($response === Password::PASSWORD_RESET){ return Redirect::route("user/profile"); } return Redirect::back() ->withInput() ->with("error", Lang::get($response)); } return View::make("user/reset", compact("token")); } protected function resetPassword($credentials) { return Password::reset($credentials, function($user, $pass){ $user->password = Hash::make($pass); $user->save(); }); } public function logout() { Auth::logout(); return Redirect::route("user/login"); } } GroupController class GroupController extends \BaseController { public function indexAction() { return View::make("group/index", [ "groups" => Group::all() ]); } public function addAction() { $form = new GroupForm(); if($form->isPosted()){ if($form->isValidForAdd()){ Group::create([ "name" => Input::get("name") ]); return Redirect::route("group/index"); } return Redirect::route("group/add")->withInput([ "name" => Input::get("name"), "errors" => $form->getErrors() ]); } return View::make("group/add", [ "form" => $form ]); } public function editAction() { $form = new GroupForm(); $group = Group::findOrFail(Input::get("id")); $url = URL::full(); if($form->isPosted()){ if($form->isValidForEdit()){ $group->name = Input::get("name"); $group->save(); $group->users()->sync(Input::get("user_id", [])); $group->resources()->sync(Input::get("resource_id", [])); return Redirect::route("group/index"); } return Redirect::to($url)->withInput([ "name" => Input::get("name"), "errors" => $form->getErrors(), "url" => $url ]); } return View::make("group/edit", [ "form" => $form, "group" => $group, "users" => User::all(), "resources" => Resource::where("secure", true)->get() ]); } public function deleteAction() { $form = new GroupForm(); if($form->isValidForDelete()){ $group = Group::findOrFail(Input::get("id")); $group->delete(); } return Redirect::route("group/index"); } } but I'm not sure how to go about fixing it especially since I was following a tutorial.